我正在尝试创建一个函数来检测字符串的数字,字母,空格和其他数字.你知道我的代码有什么问题吗?我可以将代码改进为更简单和精确吗?
谢谢!(这是修改后的代码)
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) 我正在尝试对数组进行排序,但它总是返回相同的原始输入.你知道为什么吗?
puts "Please tell me the array(separated by space, finish by enter twice):"
x = []
input = ' '
while input != ''
input = gets.chomp
x.push input
end
puts x.sort
Run Code Online (Sandbox Code Playgroud)