str_1 = "123"
str_2 = "Abc"
str_3 = "123Abc"
#用isdigit函数判断是否数字
print(str_1.isdigit())
Ture
print(str_2.isdigit())
False
print(str_3.isdigit())
False
#用isalpha判断是否字母
print(str_1.isalpha())
False
print(str_2.isalpha())
Ture
print(str_3.isalpha())
False
#isalnum判断是否数字和字母的组合
print(str_1.isalnum())
Ture
print(str_2.isalnum())
Ture
print(str_1.isalnum())
Ture
注意:如果字符串中含有除了字母或者数字之外的字符,比如空格,也会返回False。
import string
s = raw_input('input a string:
')
letters = 0
space = 0
digit = 0
others = 0
for c in s:
if c.isalpha():
letters += 1
elif c.isspace():
space += 1
elif c.isdigit():
digit += 1
else:
others += 1
print 'char = %d,space = %d,digit = %d,others = %d' % (letters,space,digit,others)