问题描述
我正在尝试计算没有空格的字符。 这是我的代码:
word = 'Ricardo Cadenas'
def string_lenght(word):
count = 0
for char in word:
count = count + 1
return count - word.count('')
print(string_lenght(word))
我的输出是-1 ???有什么想法吗?
解决方法
你打错了。我想你是想放 word.count(' ')
但你放了 word.count('')
(没有空格。)
此外,您可以初始化 count
,而不是循环计算 count = len(word)
。
正确,将“”更改为“”应该可以解决问题!