我正在尝试创建一个函数来检测字符串的数字,字母,空格和其他数字.你知道我的代码有什么问题吗?我可以将代码改进为更简单和精确吗?
谢谢!(这是修改后的代码)
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)
以下代码将任何非数字字符替换为 '',允许您使用函数 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
你不应该设置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)
| 归档时间: |
|
| 查看次数: |
66477 次 |
| 最近记录: |