I have a string with each character being separated by a pipe character (including the "|"
s themselves), for example:
"f|u|n|n|y||b|o|y||a||c|a|t"
I would like to replace all "|"
s which are not next to another "|"
with nothing, to get the result:
"funny|boy|a|cat"
I tried using mytext.replace("|", "")
, but that removes everything and makes one long word.
The replace() method replace() is a built-in method in Python that replaces all the occurrences of the old character with the new character.
To replace all occurrences of a substring in a string by a new one, you can use the replace() or replaceAll() method: replace() : turn the substring into a regular expression and use the g flag.
replace() method helps to replace the occurrence of the given old character with the new character or substring. The method contains the parameters like old(a character that you wish to replace), new(a new character you would like to replace with), and count(a number of times you want to replace the character).
Alternatively referred to as a wild character or wildcard character, a wildcard is a symbol used to replace or represent one or more characters.
This can be achieved with a relatively simple regex without having to chain str.replace
:
>>> import re
>>> s = "f|u|n|n|y||b|o|y||a||c|a|t"
>>> re.sub('\|(?!\|)' , '', s)
'funny|boy|a|cat'
Explanation: \|(?!\|) will look for a |
character which is not followed by another |
character. (?!foo) means negative lookahead, ensuring that whatever you are matching is not followed by foo.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With