知道单词中有多少个空格

Know how many spaces in words

我想知道单词列表中有多少空格

list = ["Hello       Hello Hello    Hello"]

我该怎么做?

list = ["Hello       Hello Hello    Hello"]

def readSpace():
    print(list.space())

我正在这样尝试:

谢谢。

您可以使用string.count方法来统计一个字符在字符串中出现的次数:

>>> lst = ["Hello       Hello Hello    Hello", "exa   mple"]
>>> [x.count(" ") for x in lst]
[12, 3]

因此,您可以将方法修改为:

def count_spaces(lst):
    return [x.count(" ") for x in lst]

请注意,使用 list 作为变量名是一个糟糕的变量名选择,因为它与内置的 list 冲突,因此您应该避免使用它。

您可以使用列表理解和 count() 字符串方法来完成此操作。类似于:

>>> list = ["Hello       Hello Hello    Hello"]
>>> [x.count(" ") for x in list]
 [12]