For example: The string BINGO! should be B I N G O!
I have already tried:
s = "BINGO!"
print(" ".join(s[::1]))
CodePudding user response:
I'd use regex: re.sub(r'(?<=[a-zA-Z])(?=[a-zA-Z])', ' ', 'BINGO!')
This basically says, "for every empty string in 'BINGO!' that both follows a letter and precedes a letter, substitute a space."
CodePudding user response:
I like what esramish had said, however that is a bit overcomplicated for your goal. It is as easy as this:
string = "BINGO"
print(" ".join(string))
This returns your desired output.
CodePudding user response:
You can use a single lookahead to assert a char a-z to the right and make the pattern case insensitive.
In the replacement use the full match and a space using \g<0>
(?i)[A-Z](?=[A-Z])
(?i)
Inline modifier for a case insensitive match[A-Z]
Match a single char A-Z(?=[A-Z])
Positive lookahead, assert a char A-Z to the right of the current position
See a regex demo and a Python demo.
Example
import re
print(re.sub(r'(?i)[A-Z](?=[A-Z])', '\g<0> ', 'BINGO!'))
Output
B I N G O!