Betamoo
Betamoo

Reputation: 15930

Replace substrings in python with the length of each substring

How to replace a sub-string, say words that start with capital letters, with the length of that sub-string, perhaps using regex.

For example: Using the regex "\b[A-Z]+[a-z]*\b"

"He got to go to New York"

Should be transformed into this:

"2 got to go to 3 4"

The actual scenario that I am using this in is a bit different, but I thought that scenario is more clear.

Upvotes: 1

Views: 298

Answers (2)

Omid
Omid

Reputation: 2667

This is not as succinct, but in case you want to avoid regular expressions and lambda's you can write something like this:

string = "He got to go to New York"
string = string.split()

for word in range(len(string)):
    if string[word][0].isupper():
        string[word] = str(len(string[word]))

print(" ".join(string))

Upvotes: 0

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251051

You can use re.sub for this which accepts a callable. That callable is called with match object each time a non-overlapping occurrence of pattern is found.

>>> s = "He got to go to New York"
>>> re.sub(r'\b([A-Z][a-z]*)\b', lambda m: str(len(m.group(1))), s)
'2 got to go to 3 4'

Upvotes: 4

Related Questions