简体   繁体   中英

Python 2.7: how to find the index of the first letter of each word in a string

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

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?

>>> 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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM