Python's string.whitespace is great:
>>> string.whitespace '\t\n\x0b\x0c\r '
How do I use this with a string without resorting to manually typing in '\t|\n|... etc for regex?
For example, it should be able to turn: "Please \n don't \t hurt \x0b me."
into
"Please don't hurt me."
I'd probably want to keep the single spaces, but it'd be easy enough to just go string.whitespace[:-1] I suppose.
The replaceAll() method of the String class replaces each substring of this string that matches the given regular expression with the given replacement. You can remove white spaces from a string by replacing " " with "".
The easiest approach to remove all spaces from a string is to use the Python string replace() method. The replace() method replaces the occurrences of the substring passed as first argument (in this case the space ” “) with the second argument (in this case an empty character “”).
The Strip() method in Python removes or truncates the given characters from the beginning and the end of the original string. The default behavior of the strip() method is to remove the whitespace from the beginning and at the end of the string.
There is a special-case shortcut for exactly this use case!
If you call str.split
without an argument, it splits on runs of whitespace instead of single characters. So:
>>> ' '.join("Please \n don't \t hurt \x0b me.".split()) "Please don't hurt me."
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