简体   繁体   English

有没有办法查看字符串是否包含Python中的任何符号?

[英]Is there a way to see if a string contains any symbols in Python?

I don't mean specific characters, I just mean anything that isn't alphanumeric. 我不是指特定的字符,我只是指任何不是字母数字的字符。 I've tried asking if the string contains only alphabetic and numeric characters like so: 我试过询问字符串是否只包含字母和数字字符,如下所示:

if userInput.isalpha() and userInput.isdigit() == False:
    print ("Not valid, contains symbols or spaces")

but this doesn't work and and denies all passwords I put in. 但这不起作用,并且拒绝我放入的所有密码。

Firstly, you can't be only alpha and only numeric, so your expression will always be false. 首先,您不能只是alpha而且只能是数字,因此您的表达式始终为false。

Secondly the methods isalpha() and isdigit() equate to True or False , so no need to use == False . 其次,方法isalpha()isdigit()等于TrueFalse ,因此不需要使用== False

I would suggest using .isalnum() . 我建议使用.isalnum()

If that doesn't satisfy you're requirements you should use a regex. 如果这不满足您的要求,您应该使用正则表达式。

alnum looks for both: https://docs.python.org/2/library/stdtypes.html#str.isalnum and works in Python 3.x and 2. alnum寻找两者: httpsalnum并在Python 3.x和2中工作。

Example: 例:

>>> 'sometest'.isalnum()
True
>>> 'some test'.isalnum()
False
>>> 'sometest231'.isalnum()
True
>>> 'sometest%231'.isalnum()
False
>>> '231'.isalnum()
True

You have three problems: 你有三个问题:

  • if a and b == False is not the same is if a == False and b == False ; if a and b == False 相同, if a == False and b == False ;
  • if b == False should be written if not b ; if b == False if not b ,则应写入if b == False ; and
  • You aren't using str.isalnum , which saves you from the problem anyway. 您没有使用str.isalnum ,无论如何都str.isalnum这个问题。

So it should be: 所以它应该是:

if not userInput.isalnum():

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM