Python 2.7:如何查找字符串中每个单词的第一个字母的索引

时间:2021-03-22 21:45:56

I'm looking for a way, in Python, to detect the index of the first character of each word in a string:

我正在寻找一种方法,用Python来检测字符串中每个单词的第一个字符的索引:

string = "DAY MONTH      YEAR    THIS   HAS RANDOM   SPACES"

I would like to find the position of each 'word', so this output would be:

我想找到每个'单词'的位置,所以这个输出将是:

[0, 4, 15, 23...]

Does anyone have any idea how I could achieve this?

有谁知道我怎么能做到这一点?

1 个解决方案

#1


8  

>>> import re
>>> string = "DAY MONTH      YEAR    THIS   HAS RANDOM   SPACES"
>>> [match.start() for match in re.finditer(r'\b\w', string)]
[0, 4, 15, 23, 30, 34, 43]

#1


8  

>>> import re
>>> string = "DAY MONTH      YEAR    THIS   HAS RANDOM   SPACES"
>>> [match.start() for match in re.finditer(r'\b\w', string)]
[0, 4, 15, 23, 30, 34, 43]