Dol*_*nwu 3 python position list
我想在 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)
Run Code Online (Sandbox Code Playgroud)
这个怎么样?我昨天想出了另一个解决方案。
import re
sentence = input('Please type a sentence: ')
print([match.span()[0] for match in re.finditer(' ', sentence)])
Run Code Online (Sandbox Code Playgroud)