How to Remove Spaces, Tabs, and Newlines from a String in Python?

Estimated read time 1 min read

You can remove spaces, tabs, and newlines from a string in Python using the replace() method along with the strip() method.

Here’s an example:

text = "  \t  This is a \n sample text. \t\n"

# Remove spaces, tabs, and newlines
clean_text = text.replace(" ", "").replace("\t", "").replace("\n", "").strip()

print(clean_text) # Output: "Thisisasampletext."

In this example, we have a string variable text with some spaces, tabs, and newlines. To remove these characters, we use the replace() method to replace each of them with an empty string. We then use the strip() method to remove any remaining spaces or tabs at the beginning or end of the string. The resulting string will be "Thisisasampletext.", with all the spaces, tabs, and newlines removed.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply