【问题标题】:Use enumerate() to get indices of substring within string [duplicate]使用 enumerate() 获取字符串中子字符串的索引 [重复]
【发布时间】:2022-08-19 15:14:20
【问题描述】:

我有一个较长的字符串,其中包含多个位置的字符 \'#\',我想使用循环获取索引。

string = \'#test#\' 

for index, i in enumerate(string):
        print(\"Current position of # is \", index)

结果是:

Current position of # is  0
Current position of # is  1
Current position of # is  2
Current position of # is  3
Current position of # is  4
Current position of # is  5

我如何才能添加只有在字符串中找到 \'#\' 时才会出现输出? 我试过if \'#\' in string[i]: 导致错误string indices must be integers 有没有办法在不改变字符串类型的情况下做到这一点?

  • if i == \'#\'…?!
  • i特点,索引为...index

标签: python


【解决方案1】:

需要检查字符是否为#

>>> string = '#test#'
>>> for i, char in enumerate(string):
...     if char == "#":
...         print("Current position of # is", i)
...
Current position of # is 0
Current position of # is 5

【讨论】:

    【解决方案2】:
    string = '#test#' 
    
    for index, substr in enumerate(string):
        if substr=="#":
            print("Current position of # is ", index)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-22
      • 2019-06-03
      • 2016-04-13
      • 1970-01-01
      • 1970-01-01
      • 2011-10-22
      • 1970-01-01
      • 2011-11-21
      相关资源
      最近更新 更多