【问题标题】:How can I index multiple spaces in a given string?如何索引给定字符串中的多个空格?
【发布时间】:2021-10-24 09:52:17
【问题描述】:

我试图映射给定字符串中提供空格的索引。但问题是我找不到多个空格的索引。仅显示第一个空间索引。

这是我的示例解释:

Y="Hell o World!"
print(Y.index(" "))
Output: 4

我无法映射索引上的空间:6

【问题讨论】:

标签: python string list dictionary indexing


【解决方案1】:

使用自定义函数和yield

def findall(text, pattern):
    '''Yields all the positions of the pattern in the text.'''
    i = text.find(pattern)
    while i != -1:
        yield i
        i = text.find(pattern, i+1)

Y = "Hell o World"
print(list(findall(Y, ' ')) # [4, 6]

【讨论】:

    【解决方案2】:
    import re
    Y = "Hell o World"
    occurences_list = [m.start() for m in re.finditer(' ', Y)]
    
    print(occurences_list) # [4, 6]
    

    【讨论】:

      【解决方案3】:

      您可以执行以下操作:
      根据documentation

      str.index 类似于find(),但在未找到子字符串时引发ValueError

      对于find()

      返回字符串中的最低索引,其中子字符串 sub 在切片 s[start:end]

      中找到

      在您的字符串中,4 是 python 找到空格的第一个或最低索引:' '

      >>> Y="Hell o World!"
      >>> [i for i,j in enumerate(Y) if j==' ']
      [4, 6]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-11-08
        • 1970-01-01
        • 2015-01-01
        • 2018-12-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多