[英]Is there a way to see if a string contains any symbols in Python?
我不是指特定的字符,我只是指任何不是字母數字的字符。 我試過詢問字符串是否只包含字母和數字字符,如下所示:
if userInput.isalpha() and userInput.isdigit() == False:
print ("Not valid, contains symbols or spaces")
但這不起作用,並且拒絕我放入的所有密碼。
首先,您不能只是alpha而且只能是數字,因此您的表達式始終為false。
其次,方法isalpha()
和isdigit()
等於True
或False
,因此不需要使用== False
。
我建議使用.isalnum()
。
如果這不滿足您的要求,您應該使用正則表達式。
alnum
尋找兩者: https : alnum
並在Python 3.x和2中工作。
例:
>>> 'sometest'.isalnum()
True
>>> 'some test'.isalnum()
False
>>> 'sometest231'.isalnum()
True
>>> 'sometest%231'.isalnum()
False
>>> '231'.isalnum()
True
你有三個問題:
if a and b == False
不相同, if a == False and b == False
; if b == False
if not b
,則應寫入if b == False
; 和 str.isalnum
,無論如何都str.isalnum
這個問題。 所以它應該是:
if not userInput.isalnum():
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.