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

时间:2014-07-22 02:58:33

标签: 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

它显示了这个错误:

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

10 个答案:

答案 0 :(得分:55)

这是另一种选择:

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

答案 1 :(得分:2)

你不应该设置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

答案 2 :(得分:2)

以下代码将所有非数字字符替换为'',从而使您可以使用函数len计算此类字符的数量。

import re
len(re.sub("[^0-9]", "", my_string))

字母:

import re
len(re.sub("[^a-zA-Z]", "", my_string))

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

答案 3 :(得分:0)

此代码有2个错误:

1)你应该删除这一行,因为它会将x重新命名为空列表:

x = []

2)在第一个&#34; if&#34;声明,你应该缩进&#34;字母+ = 1&#34;声明,如:

if x[i].isalpha():
    letters += 1

答案 4 :(得分:0)

忽略“修改后的代码”可能会或可能不正确的任何其他内容,导致您的问题中当前引用的错误的问题是由于使用未定义的变量调用“count”函数引起的,因为您没有引用字符串。

  • count(thisisastring222)查找名为thisisastring222的变量,以传递给名为count的函数。要使其工作,您必须先定义变量(例如使用thisisastring222 = "AStringWith1NumberInIt."),然后您的函数将使用存储在变量中的值的内容而不是变量的名称来执行您想要的操作。
  • count("thisisastring222")将字符串“thisisastring222”硬编码到调用中,这意味着count函数将使用传递给它的确切字符串。

要修复对您的功能的调用,只需在asdfkasdflasdfl222周围添加引号,将count(asdfkasdflasdfl222)更改为count("asdfkasdflasdfl222")

至于实际问题“如何计算Python中字符串的数字,字母,空格”,一目了然“修改后的代码”的其余部分看起来没问题,只是返回行没有返回相同的变量你已经在其余的代码中使用了。 要修改代码而不更改代码中的任何其他内容,请将numberword更改为digitletters,将return number,word,space,other更改为return digit,letters,space,other,或者更好的是return (digit, letters, space, other)以匹配当前行为,同时还使用更好的编码样式并明确指出返回的值类型(在本例中为元组)。

答案 5 :(得分:0)

def match_string(words):
    nums = 0
    letter = 0
    other = 0
    for i in words :
        if i.isalpha():
            letter+=1
        elif i.isdigit():
            nums+=1
        else:
            other+=1
    return nums,letter,other

x = match_string("Hello World")
print(x)
>>>
(0, 10, 2)
>>>

答案 6 :(得分:0)

#Write a Python program that accepts a string and calculate the number of digits #andletters. 
stre=input("enter the string-->")
countl=0
countn=0
counto=0
for i in stre:
    if i.isalpha():
        countl+=1
    elif i.isdigit():
        countn+=1
    else:
        counto+=1
print("The number of letters are --",countl)
print("The number of numbers are --",countn)
print("The number of characters are --",counto)

答案 7 :(得分:0)

这是您调用的错误。您正在使用参数 (asdfkasdflasdfl222) 调用代码,该参数被解释为变量。但是,您应该使用字符串 "asdfkasdflasdfl222" 调用它。

答案 8 :(得分:-1)

sample = ("Python 3.2 is very easy") #sample string  
letters = 0  # initiating the count of letters to 0
numeric = 0  # initiating the count of numbers to 0

        for i in sample:  
            if i.isdigit():      
                numeric +=1      
            elif i.isalpha():    
                letters +=1    
            else:    
               pass  
letters  
numeric  

答案 9 :(得分:-1)

输入:

1

26

sadw96aeafae4awdw2 wd100awd

import re

a=int(input())
for i in range(a):
    b=int(input())
    c=input()

    w=re.findall(r'\d',c)
    x=re.findall(r'\d+',c)
    y=re.findall(r'\s+',c)
    z=re.findall(r'.',c)
    print(len(x))
    print(len(y))
    print(len(z)-len(y)-len(w))

输出:

4

1

19

这四个数字分别是96、4、2、100 空格数= 1 字母数= 19