如何在Python中计算字符串的数字,字母,空格? [英] How to count digits, letters, spaces for a string in Python?
本文介绍了如何在Python中计算字符串的数字,字母,空格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试创建一个函数来检测一个字符串有多少个数字,字母,空格和其他字符。
I am trying to make a function to detect how many digits, letter, spaces, and others for a string.
这是我到目前为止的内容:
Here's what I have so far:
def count(x):
length = len(x)
digit = 0
letters = 0
space = 0
other = 0
for i in x:
if x[i].isalpha():
letters += 1
elif x[i].isnumeric():
digit += 1
elif x[i].isspace():
space += 1
else:
other += 1
return number,word,space,other
但是它不起作用:
>>> count(asdfkasdflasdfl222)
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
count(asdfkasdflasdfl222)
NameError: name 'asdfkasdflasdfl222' is not defined
我的代码有什么问题,如何将其改进为更简单,更精确的解决方案?
What's wrong with my code and how can I improve it to a more simple and precise solution?
推荐答案
这是另一个选择:
s = 'some string'
numbers = sum(c.isdigit() for c in s)
letters = sum(c.isalpha() for c in s)
spaces = sum(c.isspace() for c in s)
others = len(s) - numbers - words - spaces
这篇关于如何在Python中计算字符串的数字,字母,空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文