How to Remove All Whitespace from a String in Python
How to Remove All Whitespace from a String in Python
How to Remove All Whitespace from a String in Python
I need to remove all whitespace characters from a string. How can I do this in Python?
solveurit24@gmail.com Changed status to publish February 16, 2025
Whitespace characters include spaces, tabs, and newlines.
- Using
replace()Method:- Replaces spaces with an empty string.
- Code Example:
my_string = "Hello world! How are you? " no_spaces = my_string.replace(" ", "") print(no_spaces) # Output: "Helloworld!Howareyou?"
- Using List Comprehension:
- Removes all whitespace characters, not just spaces.
- Alternative Code:
my_string = "Hello world! How\tare you?\n" no_whitespace = ''.join([c for c in my_string if c != ' ' and c != '\t' and c != '\n']) print(no_whitespace) # Output: "Helloworld!Howareyou?"
- Using the
translate()Method:- More efficient and comprehensive way.
- Another Approach:
import string my_string = "Hello world! How\tare you?\n" translation_table = str.maketrans('', '', string.whitespace) no_whitespace = my_string.translate(translation_table) print(no_whitespace) # Output: "Helloworld!Howareyou?"
- Explanation:
- The
translate()method is more efficient and removes all whitespace characters in a single call.
- The
solveurit24@gmail.com Changed status to publish February 16, 2025