在 Python 中,可以使用 input() 函数从键盘输入字符串。例如:
string = input('请输入字符串: ')
然后,可以使用字典来统计字符串中数字出现的次数。首先,可以创建一个空字典,然后遍历字符串中的每一个字符,如果这个字符是数字,就将它作为字典的键,并将其值加 1。
count = {}
for char in string:
if char.isdigit():
if char in count:
count[char] += 1
else:
count[char] = 1
最后,可以使用循环来遍历字典并输出结果。文章来源:https://www.toymoban.com/news/detail-745518.html
for key, value in count.items():
print(f'数字 {key} 出现了 {value} 次')
完整的代码如下:文章来源地址https://www.toymoban.com/news/detail-745518.html
string = input('请输入字符串: ')
count = {}
for char in string:
if char.isdigit():
if char in count:
count[char] += 1
else:
count[char] = 1
for key, value in count.items():
print(f'数字 {key} 出现了 {value} 次')
到了这里,关于python从键盘输入-个字符串,统计该字符串中各数字出现的次数。的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!