Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preferred way to remove whitespace from a string [closed]

Tags:

People also ask

How do I remove a whitespace character 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 "".

Which function is used to remove whitespace from the string?

The trim() function removes whitespace and other predefined characters from both sides of a string.

Which method removes whitespace?

strip(): The strip() method is the most commonly accepted method to remove whitespaces in Python. It is a Python built-in function that trims a string by removing all leading and trailing whitespaces.

Which method is used to remove whitespace from the beginning and end of a string?

The trim() method will remove both leading and trailing whitespace from a string and return the result.


I want to remove all spaces from a string.

" as fa sdf sdfsdf "

The result would be:

"asfasdfsdfsdf"

There are several ways I can think of to achieve this, and I'm wondering which one is the best.

1.

"".join(" as fa   sdf sdfsdf ".split())

2.

" as fa   sdf sdfsdf ".replace(" ", "")

And I assume that there are more.
Which one is preferred?