How to remove all whitespace in a string?

To remove leading and trailing spaces from a string, you can use the str.strip() method:

>>> "  hello  apple  ".strip()
'hello  apple'

If you want to remove all space characters from a string, you can use the str.replace() method. Note that this only removes the standard ASCII space character (’ ’ U+0020) and not any other whitespace characters:

>>> "  hello  apple  ".replace(" ", "")
'helloapple'

To remove duplicated spaces from a string, you can use a combination of str.split() and str.join():

>>> " ".join("  hello  apple  ".split())
'hello apple'

These methods allow you to manipulate and clean up spaces within strings in Python.