I have this string:
mystring = 'Here is some text I wrote '
How can I substitute the double, triple (...) whitespace chracters with a single space, so that I get:
mystring = 'Here is some text I wrote'
Use the re. sub() method to replace multiple spaces with a single space, e.g. result = re. sub(' +', ' ', my_str) .
The metacharacter “\s” matches spaces and + indicates the occurrence of the spaces one or more times, therefore, the regular expression \S+ matches all the space characters (single or multiple). Therefore, to replace multiple spaces with a single space.
Using regexes with "\s" and doing simple string. split()'s will also remove other whitespace - like newlines, carriage returns, tabs.
A simple possibility (if you'd rather avoid REs) is
' '.join(mystring.split())
The split and join perform the task you're explicitly asking about -- plus, they also do the extra one that you don't talk about but is seen in your example, removing trailing spaces;-).
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