how to add space after every word and separate digits from word?

Question:

here is my string

text = 'EffectsRelaxed96% VotedHappy79% VotedEuphoric67% Voted'

I tried this:

add_space_after_word =  re.sub(r"(w)([A-Z])", r"1 2", text)
>>>'Effects Relaxed96% Voted Happy79% Voted Euphoric67% Voted'
seperate_digites_from_words = 'Effects Relaxed96% Voted Happy79% Voted Euphoric67% Voted'
re.sub(r"(dd)", r" 1", seperate_digites_from_words)
>>>'Effects Relaxed 96% Voted Happy 79% Voted Euphoric 67% Voted'

my expected result will be:

'Effects: Relaxed 96% Voted, Happy 79% Voted, Euphoric 67% Voted'

is there any way I can do this in a single line of code instead of writing two line of code? also I want to add comma after word Voted and want to add semicolon after word Effects.

Asked By: boyenec

||

Answers:

You can use

import re
text = 'EffectsRelaxed96% VotedHappy79% VotedEuphoric67% Voted'
print( re.sub(r'([a-z])([A-Z0-9])', r'1 2', text).replace("Effects", "Effects:").replace("Voted", "Voted,").rstrip(',') )
# => Effects: Relaxed 96% Voted, Happy 79% Voted, Euphoric 67% Voted

See the Python code demo.

The ([a-z])([A-Z0-9]) regex matches a lowercase letter (capturing into Group 1) and then an uppercase letter or digit (capturing into Group 2). The replacement is Group 1 and Group 2 with a space between them.

The colon and commas are added using mere str.replace, since the words are known.

Answered By: Wiktor Stribiżew
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.