如何检查字符串是否有任何特殊字符?

时间:2019-07-16 17:40:58

标签: python

我想知道是否可以使用.isnumeric()或.isdigit()之类的方法来检查字符串是否具有特殊字符。如果没有,我该如何使用正则表达式进行检查?我只找到有关检查它是否包含字母或数字的答案。

7 个答案:

答案 0 :(得分:3)

检查任何不是字母数字的字符,例如:

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

答案 1 :(得分:3)

尝试一下:

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

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

答案 2 :(得分:2)

使用string.printabledoc):

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.")

答案 3 :(得分:1)

假定空格不算作特殊字符。

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',
        '12?3123',
        'hnfgbg'
    ]
    for it in texts:
        if has_special_char(it):
            print(it)

输出:

asdsgbn!@$^Y$
12?3123

答案 4 :(得分:0)

在寻找更好的解决方案时,这是一种不理想但可行的方法:

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

答案 5 :(得分:0)

您可以像这样简单地使用字符串方法isalnum()

firstString = "This string ha$ many $pecial ch@racters"
secondString = "ThisStringHas0SpecialCharacters"
print(firstString.isalnum())
print(secondString.isalnum())

这将显示:

False
True

如果您想了解更多关于here的信息。

答案 6 :(得分:0)

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)