【问题标题】:Count characters in a string without spaces计算字符串中没有空格的字符
【发布时间】:2021-03-23 22:41:53
【问题描述】:

我正在尝试计算没有空格的字符。 这是我的代码:

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 ???有什么想法吗?

【问题讨论】:

  • 仅供参考……这个string_lenght(word) 的单词length 拼写错误。你可能想解决这个问题,因为它确实让人分心。 [咧嘴一笑]

标签: counting


【解决方案1】:

你有一个错字。我认为您的意思是输入word.count(' '),但您输入了word.count('')(没有空格。)
此外,您可以初始化count = len(word),而不是循环计算count

【讨论】:

  • 你的是一个简化的解决方案,谢谢
【解决方案2】:

正确,将“”更改为“”应该可以解决问题!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-06
    • 2014-04-02
    相关资源
    最近更新 更多