有没有一种方法可以检查字符串是否包含特殊字符?

28
我想知道是否有一种方法可以检查字符串中是否有特殊字符。据我所知,没有像 .isnumeric().isdigit() 这样的内置函数来执行此操作。
例如,对于输入 测试! 我希望程序返回 True,或者输入 无特殊字符 返回False
我所说的特殊字符是指 *&% 等字符。完整的列表可以在这里找到。

1
你能提供一个例子吗? - Slouei
1
欢迎来到StackOverflow。在您的上下文中,“特殊字符”是什么意思?在这类问题中,您需要非常清晰和具体。 - Rory Daulton
2
你指的是哪些特殊字符?不是文本或数字吗? - Fredrik
@Fredrik @%-_)(.... - user11786059
1
所有的字符中哪些是特殊的?从好的方面讲,它们有两个维度:块(如那个网页所示)和一般类别。从坏的方面来说,文字还有一些非常特殊的特性,比如组合字符、正常形式、反向编码点和变量选择器(比如肤色)。易混淆字符可能会成为一个问题,并因此对你来说而“特殊”。简而言之,你现在的问题太宽泛了。 - Tom Blodget
7个回答

41

检查任何非字母数字的字符,比如:

any(not c.isalnum() for c in mystring)

7
对于一个仅由空白字符组成的字符串,这将返回真。 - abdusco
将字符串中的空格替换为空,并进行去除操作。 - Raul Chiarella

23

试一试:

special_characters = ""!@#$%^&*()-+?_=,<>/""
s=input()
# Example: $tackoverflow

if any(c in special_characters for c in s):
    print("yes")
else:
    print("no")
 
# Response: yes

请问您能否展示一下您的代码片段来回答这个问题?请务必遵循StackOverflow关于如何回答问题的指南。 - ndrwnaguib
3
OWASP 推荐以下特殊字符列表用于密码:(Python 字符串转义)" !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~" 来源:https://owasp.org/www-community/password-special-characters - CPSuperstore
1
你也可以使用 "string.punctuation" 作为特殊字符列表 https://docs.python.org/3/library/string.html#string.punctuation - Teazane
我会在我的应用程序中使用这个。我不打算使用正则表达式。这个很好用。 - codingbruh
1
这里的 'c' 代表什么? - Liyanna

18

使用 string.printable (文档):

text = 'This is my text with special character ()'

from string import printable

if set(text).difference(printable):
    print('Text has special characters.')
else:
    print("Text hasn't special characters.")

输出:

Text has special characters.

编辑:仅测试ASCII字符和数字:

text = 'text%'

from string import ascii_letters, digits

if set(text).difference(ascii_letters + digits):
    print('Text has special characters.')
else:
    print("Text hasn't special characters.")

7
一种不完美但有潜力的方法是在我寻找更好的解决方案时使用它:
special_char = False
for letter in string:
    if (not letter.isnumeric() and not letter.isdigit()):
        special_char = True
        break

更新:尝试这个方法,它会检查字符串中是否存在正则表达式。所示的正则表达式适用于任何非字母数字字符。

import re
word = 'asdf*'
special_char = False
regexp = re.compile('[^0-9a-zA-Z]+')
if regexp.search(word):
    special_char = True

使用isalnum()怎么样? - static const

4
假设空格不计入特殊字符。
def has_special_char(text: str) -> bool:
    return any(c for c in text if not c.isalnum() and not c.isspace())


if __name__ == '__main__':
    texts = [
        'asdsgbn!@$^Y$',
        '    ',
        'asdads 345345',
        '123123',
        'hnfgbg'
    ]
    for it in texts:
        if has_special_char(it):
            print(it)

输出:

asdsgbn!@$^Y$
123123

3
Geeksforgeeks 使用正则表达式提供了一个非常好的例子。
原始答案翻译为“最初的回答”。
特殊字符包括 [@_!#$%^&*()<>?/\|}{~:]。
来源-->https://www.geeksforgeeks.org/python-program-check-string-contains-special-character/
# Python program to check if a string 
# contains any special character 

# import required package 
import re 

# Function checks if the string 
# contains any special character 
def run(string): 

    # Make own character set and pass  
    # this as argument in compile method 
    regex = re.compile('[@_!#$%^&*()<>?/\|}{~:]') 

    # Pass the string in search  
    # method of regex object.     
    if(regex.search(string) == None): 
        print("String is accepted") 

    else: 
        print("String is not accepted.") 


# Driver Code 
if __name__ == '__main__' : 

    # Enter the string 
    string = "Geeks$For$Geeks"

    # calling run function  
    run(string) 

2
您可以简单地使用字符串方法isalnum(),如下所示:最初的回答
firstString = "This string ha$ many $pecial ch@racters"
secondString = "ThisStringHas0SpecialCharacters"
print(firstString.isalnum())
print(secondString.isalnum())

最初的回答:这会显示:
False
True

如果你想了解更多相关信息,可以在这里查看。

"Original Answer"的翻译是"最初的回答"。


最简单的解决方案,您不需要遍历字符。 - Muhammad Haseeb

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接