原题链接:http://www.runoob.com/python/python-exercise-example17.html
题目:输入一行字符,分别统计出其中 英文字母、空格、数字和其它字符的个数。(不是中英文字符。。。。)
我的代码:
def fun(): s=input("please enter a string: ") le=0 sp=0 nu=0 others=0 for i in s: if i.isalpha(): le+=1 elif i.isdigit(): nu+=1 elif i.isspace(): sp+=1 else: others+=1 print("length=%d,char=%d,space=%d,digit=%d,others=%d" %(len(s),le,sp,nu,others)) if __name__ =='__main__': fun()
思考:
学会了python自带的isalpha() isspace() isdigit()函数,注意都是针对str可以使用的!
str.isalpha() 检测字符串是否只由字母组成。
str.isspace() 检测字符串是否只由空白字符( ' ' 等)组成。
str.isdigit() 检测字符串是否只由数字组成。
熟练掌握就能解决这个问题了~
此外,还可以拓展一些方法:
s.isalnum() 所有字符都是数字或者字母
s.islower() 所有字符都是小写
s.isupper() 所有字符都是大写
s.istitle() 所有单词都是首字母大写,像标题