开发者

In Python, how do I check if a string has alphabets or numbers?

开发者 https://www.devze.com 2023-03-19 18:10 出处:网络
If the string has an alphabet or a number, return true. Otherwise, return false.开发者_开发知识库

If the string has an alphabet or a number, return true. Otherwise, return false.开发者_开发知识库

I have to do this, right?

return re.match('[A-Z0-9]',thestring)


Use thestring.isalnum() method.

>>> '123abc'.isalnum()
True
>>> '123'.isalnum()
True
>>> 'abc'.isalnum()
True
>>> '123#$%abc'.isalnum()
>>> a = '123abc' 
>>> (a.isalnum()) and (not a.isalpha()) and (not a.isnumeric())
True
>>> 


If you want to check if ALL characters are alphanumeric:

  • string.isalnum() (as @DrTyrsa pointed out), or
  • bool(re.match('[a-z0-9]+$', thestring, re.IGNORECASE))

If you want to check if at least one alphanumeric character is present:

import string
alnum = set(string.letters + string.digits)
len(set(thestring) & alnum) > 0

or

bool(re.search('[a-z0-9]', thestring, re.IGNORECASE))


It might be a while, but if you want to figure out if the string at at least 1 alphabet or numeral, we could use

re.match('.*[a-zA-Z0-9].*', yourstring)


What about

stringsample.isalpha() 

method?

0

精彩评论

暂无评论...
验证码 换一张
取 消