How to strip all whitespace from string
No time for chit-chat? Here's your quick whitespace-busting code:
Use replace() to wipe out spaces. Use join() with split() for a total whitespace purge.
Kiss Special Whitespaces Goodbye with Regex
Occasionally, you'll want to remove other white characters (like tab \t, newline \n, etc). Good news! Regex is your Swiss army knife for this:
This will deal with standard and Unicode whitespace like a ninja. Remember, \s is your go-to guy for wide range of Unicode whitespace characters.
Be Smart: Precompile your Regex Expressions
Planning to knock out whitespaces in a loop or repetitively in your code? Here's a pro tip:
- Compile the regex pattern first
- Then, use the pattern's sub() method to replace the whitespace:
By precompiling the regex, you're basically giving Python a map β so it doesn't get lost (and slow) re-reading directions each time.
For the Tricky Buggers: Translations and Unicode
Stumble upon not only spaces, but Unicode oddities like zero-width spaces (\u200B) or ideographic spaces? Say hello to str.translate():
Python 3.x:
Python 2.x:
This method furnishes a translation table and strips specified characters efficiently β like a veteran space hunter.
Need a surgical strike? Custom Whitespace Handling
Sometimes, whitespaces are like unwanted guests. You might want to keep some, remove some. strip(), replace(), and regex can come up with a custom cleaning plan:
- Use
strip()for your door policy: No leading and trailing spaces allowed. - Deploy
replace()for interior maintenance: Remove spaces inside. - Regex is your ceremony planner: When you want to remove combinations of whitespaces with a rule.
Preparing for the Unexpected
- David Vs Goliath: Large strings can be heavy on memory usage. Be careful with operations creating string copies.
- Lost in Translation: Beyond simple ASCII whitespace, you may encounter the wide world of Unicode whitespace.
- Performance Anxiety: Working with large datasets? Choose methods that won't get stage fright with huge input.
Was this article helpful?