如何检查字符串中的特殊字符?

编程入门 行业动态 更新时间:2024-10-11 19:15:30
本文介绍了如何检查字符串中的特殊字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我只能在我的程序中使用一个字符串,如果它不包含除下划线 _ 之外的特殊字符.我该如何检查?

I can only use a string in my program if it contains no special characters except underscore _. How can I check this?

我尝试使用 unicodedata 库.但是特殊字符只是被标准字符替换了.

I tried using unicodedata library. But the special characters just got replaced by standard characters.

推荐答案

你可以像这样使用 string.punctuation 和 any 函数

You can use string.punctuation and any function like this

import string invalidChars = set(string.punctuation.replace("_", "")) if any(char in invalidChars for char in word): print "Invalid" else: print "Valid"

有了这条线

invalidChars = set(string.punctuation.replace("_", ""))

我们正在准备一个不允许使用的标点符号列表.由于您希望允许 _,我们正在从列表中删除 _ 并准备新的集合为 invalidChars.因为在集合中查找速度更快.

we are preparing a list of punctuation characters which are not allowed. As you want _ to be allowed, we are removing _ from the list and preparing new set as invalidChars. Because lookups are faster in sets.

any 函数将返回True.

正如评论中所问,这是正则表达式解决方案.取自 stackoverflow/a/336220/1903116

As asked in the comments, this is the regular expression solution. Regular expression taken from stackoverflow/a/336220/1903116

word = "Welcome" import re print "Valid" if re.match("^[a-zA-Z0-9_]*$", word) else "Invalid"

更多推荐

如何检查字符串中的特殊字符?

本文发布于:2023-11-12 13:33:31,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1581645.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   特殊字符

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!