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"(\d\d)", 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.
CodePudding user response:
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.