Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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'

Solution 2:

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)):
    ifstring[word][0].isupper():
        string[word] = str(len(string[word]))

print(" ".join(string))

Post a Comment for "Replace Substrings In Python With The Length Of Each Substring"