如何计算Python中字符串的数字,字母和空格

ray*_*ray 17 python

我正在尝试创建一个函数来检测字符串的数字,字母,空格和其他数字.你知道我的代码有什么问题吗?我可以将代码改进为更简单和精确吗?

谢谢!(这是修改后的代码)

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
Run Code Online (Sandbox Code Playgroud)

它显示了这个错误:

>>> count(asdfkasdflasdfl222)
Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    count(asdfkasdflasdfl222)
NameError: name 'asdfkasdflasdfl222' is not defined
Run Code Online (Sandbox Code Playgroud)

Ósc*_*pez 65

这是另一种选择:

s = 'some string'

numbers = sum(c.isdigit() for c in s)
words   = sum(c.isalpha() for c in s)
spaces  = sum(c.isspace() for c in s)
others  = len(s) - numbers - words - spaces
Run Code Online (Sandbox Code Playgroud)

  • +1分离任务时,解决方案更清晰.干得好!为了加快速度,可以考虑使用*itertools.imap()*,如下所示:``numbers = sum(imap(str.isdigit,s))``.在初始调用之后,它将以C-speed运行,没有纯python步骤,也没有方法查找. (12认同)

bri*_*bed 9

以下代码将任何非数字字符替换为 '',允许您使用函数 len 计算此类字符的数量。

import re
len(re.sub("[^0-9]", "", my_string))
Run Code Online (Sandbox Code Playgroud)

按字母顺序:

import re
len(re.sub("[^a-zA-Z]", "", my_string))
Run Code Online (Sandbox Code Playgroud)

更多信息 - https://docs.python.org/3/library/re.html


ssh*_*124 3

你不应该设置x = []. 即为您输入的参数设置一个空列表。此外,使用Python的for i in x语法如下:

for i in x:
    if i.isalpha():
        letters+=1
    elif i.isnumeric():
        digit+=1
    elif i.isspace():
        space+=1
    else:
        other+=1
Run Code Online (Sandbox Code Playgroud)