python 练习10 ASCll码判断字符类型

题目:输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。

首先先介绍python 获取ascll码的函数:ord()

这样就可以接下来看代码了:

s=input("intput:")
letters = 0
space = 0
digit = 0
others = 0
for c in s:
	if ord(c) in range(65,91):
		letters += 1
	elif ord(c) in range(97,123):
		letters += 1
	elif ord(c)==32:
		space += 1
	elif ord(c) in range(48,58):
		digit += 1
	else:
		others += 1
print("char=%d space=%d digit=%d others=%d"%(letters,space,digit,others))

当然,这是一种相对于麻烦的方法,python中有相应的函数可以直接判断:

str.isalnum()  所有字符都是数字或者字母,为真返回 Ture,否则返回 False。

str.isalpha()   所有字符都是字母(当字符串为中文时, 也返回True),为真返回 Ture,否则返回 False。

str.isdigit()     所有字符都是数字,为真返回 Ture,否则返回 False。

str.islower()    所有字符都是小写,为真返回 Ture,否则返回 False。

str.isupper()   所有字符都是大写,为真返回 Ture,否则返回 False。

str.istitle()      所有单词都是首字母大写,为真返回 Ture,否则返回 False。

str.isspace()   所有字符都是空白字符,为真返回 Ture,否则返回 False。

根据这些函数我们可以再写一个代码,这样就相对来说比较简单了:

s=input("intput:")
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))
发布了77 篇原创文章 · 获赞 7 · 访问量 9095

猜你喜欢

转载自blog.csdn.net/qq_41886231/article/details/90487672