[python] How do I remove whitespace from the end of a string in Python?

I need to remove whitespaces after the word in the string. Can this be done in one line of code?

Example:

string = "    xyz     "

desired result : "    xyz" 

This question is related to python

The answer is


>>> "    xyz     ".rstrip()
'    xyz'

There is more about rstrip in the documentation.


You can use strip() or split() to control the spaces values as in the following:

words = "   first  second   "

# Remove end spaces
def remove_end_spaces(string):
    return "".join(string.rstrip())


# Remove the first and end spaces
def remove_first_end_spaces(string):
    return "".join(string.rstrip().lstrip())


# Remove all spaces
def remove_all_spaces(string):
    return "".join(string.split())


# Show results
print(words)
print(remove_end_spaces(words))
print(remove_first_end_spaces(words))
print(remove_all_spaces(words))