Nathan White
Nathan White

Reputation: 1080

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?

Upvotes: 2

Views: 545

Answers (1)

jamylak
jamylak

Reputation: 133544

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

Upvotes: 8

Related Questions