'''
如何检测字符串是否位数字、数字和字母混合形式
'''
#检测字符串是否由字母或数字组成 isalnum
'''
Return True if the string is an alpha-numeric string, False otherwise.
A string is alpha-numeric if all characters in the string are alpha-numeric and there is at least one character in the string
'''
a = '123'
print(a.isalnum())#True
b = 'shaw'
print(b.isalnum())#True
c = 'shaw123'
print(c.isalnum())#True
d = 'th 123'
print(d.isalnum())#False
#检测字符串是否只由字母组成 isalpha
'''
Return True if the string is an alphabetic string, False otherwise.
A string is alphabetic if all characters in the string are alphabetic and there is at least one character in the string
'''
a = '123'
print(a.isalpha())#False
b = '123shaw'
print(b.isalpha())#False
c = 'shaw'
print(c.isalpha())#True
d = 'sha w'
print(d.isalpha())#False
#检测字符串是否只由数字组成
'''
Return True if the string is a digit string, False otherwise.
A string is a digit string if all characters in the string are digits and there is at least one character in the string.
'''
a = '123'
print(a.isdigit())#True
b = 'shaw'
print(b.isdigit())#False
c = '123shaw'
print(c.isdigit())#False
'''
怎样将一个字符串转为数字才安全
'''
s = '12345a'
if s.isdigit():
print(int(s))
else:
print(s,' is not a num')
try:
print(int(s))
except Exception as e:
print(repr(e))
如何检测一个字符串是否为数字
最新推荐文章于 2023-05-08 21:51:52 发布