【问题标题】:How do I get the position of a string inside a list in Python? [duplicate]如何在 Python 的列表中获取字符串的位置? [复制]
【发布时间】:2021-07-16 13:56:27
【问题描述】:

我想在 Python 的列表中获取字符串的位置?我该怎么做?

例如,当用户提供一个句子“你好,我的名字是Dolfinwu”时,我预先将整个句子变成了一个列表,我想在这里得到每个“o”的位置,我该怎么做?在这种情况下,第一个“o”的位置是“4”,第二个“o”的位置是“18”。但是很明显,用户会使用不同的词输入不同的句子,那么在这种不可预知的情况下,如何获取特定字符串值的位置呢?

我已经尝试过如下代码。我知道它包含语法错误,但我想不出更好的东西。

sentence = input('Please type a sentence: ')
space = ' '

for space in sentence:
    if space in sentence:
        space_position = sentence[space]
        print(space_position)

【问题讨论】:

  • 您能否提供更多预期输入和输出的示例?列表表示形式是什么样的? “我的名字 Hello”的预期输出是什么?
  • print([(item, index) for index, item in enumerate(string) if item == 'o']) 是这样的吗?
  • 这能回答你的问题吗? How to find all occurrences of a substring?
  • 欢迎来到 StackOverflow。请发布您的代码,说明您是如何解决问题的,以及哪些问题不起作用。

标签: python list position


【解决方案1】:

这个怎么样?我昨天想出了另一个解决方案。

import re
sentence = input('Please type a sentence: ')
print([match.span()[0] for match in re.finditer(' ', sentence)])

【讨论】:

  • 要获取每次出现的开始,使用 re.finditer 并提取 span 属性的第一项。
【解决方案2】:

你的这段代码有点乱


space = ' ' #  This is fine but redundant 
for space in sentence: # Shouldn't reuse variable names. Should be <for char in sentence. But I wouldn't use that either since we don't need the char it self but the index
    if space in sentence: #Should be <if char == space> Your just returns a True if there's a single space anywhere in the string. Assuming it's using the correct variable named space. Honestly I don't know what this code will do since I didn't run it :P
        space_position = sentence[space]
        print(space_position)

这是我要做的,因为我也是初学者,所以可以做得更好。

sentence = input('Please type a sentence: ')


for i in range(len(sentence)):
    if sentence[i] == " ":
        print(i)

#>>>Please type a sentence: A sentence and spaces
#>>>1
#>>>10
#>>>14

【讨论】:

  • 列表理解和事情可能会在一行中得到相同的结果,但我想这会让你感到困惑。
  • 对于将来阅读本文的任何人,您也可以使用 enumerate 函数使其变得更好。
【解决方案3】:

您的第一个代码中也有一个错误,其中行 space_position = sentence[space] 使用字符串(如果我是正确的)作为行中列表的索引,我认为它应该是一个整数。所以我会怎么做

sentence = input('Please type a sentence: ')  # Asks the user to input the sentence
space_position = []  # The list where the list indexes of the spaces will be stored (can work for any other symbol)

for i in range(len(sentence)):  # Scans every single index of the list
    if sentence[i] == " ":  # Determines whether if the value of the specific list index is the chosen string value
    # (The value could be swapped for another one aside from strings)
        print(i)  # Print out the index where the value is the chosen string value

其余的费用与@pudup 发布的一样

附:我也是初学者,所以我的代码可能不是最好的解决方案或有语法错误,如果它们不起作用或效率不高,请道歉。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-23
    • 2012-10-22
    • 2019-12-10
    • 2011-01-18
    • 1970-01-01
    相关资源
    最近更新 更多