1

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.

0

2 Answers 2

4

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'
Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

This would fail with numbers/punctuation symbols.. E.g: He got to New York, the most .. city.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.