Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove whitespace in Python using string.whitespace

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.

like image 924
Alex Avatar asked Dec 14 '09 02:12

Alex


People also ask

How do you remove white spaces from a string?

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 "".

How do you replace a space in a string in Python?

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 “”).

What does Strip () do in Python?

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.


1 Answers

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." 
like image 117
bobince Avatar answered Oct 13 '22 00:10

bobince