我正在寻找一种方法,用Python来检测字符串中每个单词的第一个字符的索引:
string = "DAY MONTH YEAR THIS HAS RANDOM SPACES"
我想找到每个'单词'的位置,所以这个输出将是:
[0, 4, 15, 23...]
有谁知道我怎么能做到这一点?
答案 0 :(得分: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]