How to Remove Whitespace from a String

93 views

How to Remove Whitespace from a String

How to Remove Whitespace from a String

I need to remove all whitespace characters from a string. How can I do this?

solveurit24@gmail.com Changed status to publish February 16, 2025
0

Whitespace includes spaces, tabs, and newlines. You can remove all of them using a list comprehension or the replace() method.

Code Example:

def remove_whitespace(s):
    return ''.join([c for c in s if c not in (' ', '\t', '\n')])

# Example usage
text = "Hello\tworld!\n How are you?"
print(remove_whitespace(text))  # Output: "Helloworld!Howareyou?"

This function iterates through each character in the string and joins together only those that are not whitespace.

solveurit24@gmail.com Changed status to publish February 16, 2025
0
You are viewing 1 out of 1 answers, click here to view all answers.