python3中,len()、isalpha()、isspace()、isdigit()、isalnum()实例


实例:使用while循环

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import string

s1 = input('请输入一个字符串:\n')

letters = 0

space = 0

digit = 0

others = 0

i = 0

while i < len(s1):

c = s1[i]

i += 1

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))

备注: len() 方法返回对象(字符、列表、元组等)长度或项目个数;

isalpha() 如果字符串至少有一个字符并且所有字符都是字母则返回 True,否则返回 False;

isspace() 如果字符串中只包含空格,则返回 True,否则返回 False;

isdigit() 如果字符串只包含数字则返回 True 否则返回 False。

实例:使用for循环

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import string

s2=input('请输入一个字符串:')

letters=0

space=0

digit=0

others=0

i=0

for c in s2:

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))

isdigit() 如果字符串只包含数字则返回 True 否则返回 False。

1
2
3
4
5
6
7
print('12345'.isdigit())  #纯数字      执行结果:True

print('①②'.isdigit()) #带圈的数字 执行结果:True

print('汉字'.isdigit()) #汉字 执行结果:False

print('%#¥'.isdigit()) #特殊符号 执行结果:False

isalpha() 如果字符串至少有一个字符并且所有字符都是字母则返回 True,否则返回 False;

1
2
3
4
5
print('abc汉字'.isalpha())  #汉字+字母  执行结果:True

print('ab字134'.isalpha()) #包含数字 执行结果:False

print('*&&'.isalpha()) #特殊符号 执行结果:False

isalnum()中至少有一个字符且如果S中的所有字符都是字母数字,那么返回结果就是True;否则,就返回False

1
2
3
4
5
print('abc汉字1'.isalnum())  #字母+汉字+数字  执行结果:True

print('①②③'.isalnum()) #带圈的数字 执行结果:True

print('%……&'.isalnum()) #特殊符号 执行结果:False

注意点:

1.python官方定义中的字母:大家默认为英文字母+汉字即可

2.python官方定义中的数字:大家默认为阿拉伯数字+带圈的数字即可

相信只要理解到这两点,这三个函数的在使用时的具体返回值,大家就很明确了~~


文章作者: GoodTimeGGB
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 GoodTimeGGB !
评论
  目录