【基础入门题】2021.11.29
给定一行字符串,分别统计出其中英文字母、数字、空格和其它字符的个数。
编程语言:包括但不限于Python
题目来源:派森特给站每日刷题频道
————————————————
方法一:
def Character(Str):
letters,digits,spaces,others = 0,0,0,0
for s in Str:
if 'a'<=s<='z' or 'A'<=s<='Z':
letters += 1
elif '0'<=s<='9':
digits += 1
elif s==' ':
spaces += 1
else:
others += 1
return letters,digits,spaces,others
print(Character('I am Hann Yang, my email is [hann@126.com].'))
方法二:与string库中的几个常量比较
def Character(Str):
import string
letters,digits,spaces,others = 0,0,0,0
for s in Str:
if s in string.ascii_letters:
letters += 1
elif s in string.digits:
digits += 1
elif s in string.whitespace: #whitespaqce除了空格还包括'\t\n\r\x0b\x0c'
spaces += 1
else:
others += 1
return letters,digits,spaces,others
print(Character('I am Hann Yang, my email is [hann@126.com].'))
欢迎加入csdn社区! https://bbs.csdn.net/forums/PythonTogether
https://bbs.csdn.net/forums/PythonTogether
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/boysoft2002/article/details/121777272
内容来源于网络,如有侵权,请联系作者删除!