python分别统计出其中英文字母、空格、数字和其它字符的个数
1.统计字符串中子串个数如下所示:#s = input('请输入一个字符串:\n')s = 'hello world,hello friend's1 = 'hello'print(s.count(s1))# 22.计算字符串中英文字母,空格,数字和其它字符的个数import strings = input('请输入一个字符串:\n')letters = 0# 统...
文章共284字 · 阅读需要大约1分钟
一键AI生成摘要,助你高效阅读
问答
·
1.统计字符串中子串个数如下所示:
#s = input('请输入一个字符串:\n')
s = 'hello world,hello friend'
s1 = 'hello'
print(s.count(s1)) # 2
2.计算字符串中英文字母,空格,数字和其它字符的个数
import string
s = input('请输入一个字符串:\n')
letters = 0 # 统计字母个数
space = 0 # 统计空格个数
digit = 0 # 统计数字个数
others = 0 # 统计其他字符个数
i = 0
while i < len(s):
oneword = s[i] # 获取每个位置的值
i += 1
if oneword.isalpha(): # 判断是否是字母
letters += 1
elif oneword.isdigit(): # 判断是否为数字
digit += 1
elif oneword.isspace(): # 判断是否为空格
space += 1
else:
others += 1
print("[%s]中字母个数=%d,数字个数=%d,空格个数=%d,其他字符个数=%d" % (s,letters,digit,space,others))
运行结果
请输入一个字符串:
hello world 123,#@
[hello world 123,#@]中字母个数=10,数字个数=3,空格个数=2,其他字符个数=3
更多推荐
已为社区贡献4条内容
所有评论(0)