如何在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
我的代码哪里出问题了?我该如何改进,让它变得更简单和准确呢?
12 个回答
1
不管你“修订后的代码”还有没有其他问题,导致你提问中出现错误的原因是因为你在调用“count”函数时用了一个未定义的变量,因为你没有把字符串用引号括起来。
count(thisisastring222)
是在寻找一个叫做 thisisastring222 的变量来传给 count 函数。要让这个工作,你必须在之前定义这个变量(比如用thisisastring222 = "AStringWith1NumberInIt."
),这样你的函数才能处理这个变量里存储的值,而不是变量的名字。count("thisisastring222")
是把字符串 "thisisastring222" 直接写进函数调用里,这样 count 函数就会处理你传给它的这个确切字符串。
要修正你对函数的调用,只需在 asdfkasdflasdfl222
周围加上引号,把 count(asdfkasdflasdfl222)
改成 count("asdfkasdflasdfl222")
。
至于你实际的问题“如何在 Python 中计算字符串的数字、字母和空格”,从表面上看,其他的“修订代码”看起来没问题,只是返回的那一行没有返回你在其他代码中使用的变量。要修复这个问题而不改变代码的其他部分,把 number
和 word
改成 digit
和 letters
,把 return number,word,space,other
改成 return digit,letters,space,other
,或者更好的是 return (digit, letters, space, other)
,这样可以保持当前的行为,同时使用更好的编码风格,并明确返回的值类型(在这种情况下是一个元组)。
2
要计算一个字符串中的字母数量:
def iinn(): # block for numeric strings
b=(input("Enter numeric letter string "))
if b.isdigit():
print (f"you entered {b} numeric string" + "\n")
else:
letters = sum(c.isalpha() for c in b)
print (f"in the string {b} are {letters} alphabetic letters")
print("Try again...","\n")
while True:
iinn()
一组数字字符串将会是反向排列的:
numbers = sum(c.isdigit() for c in b)
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
10
下面的代码会把所有非数字的字符替换成空字符串,这样你就可以用len这个函数来计算这些字符的数量。
import re
len(re.sub("[^0-9]", "", my_string))
字母:
import re
len(re.sub("[^a-zA-Z]", "", my_string))
140
这里还有一个选择:
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 - letters - spaces