rstrip(): removing spaces and chars from the end of a string in Python

Use the rstrip() method to remove spaces from the end of a string.

regular_text = "This is a regular text.   "

no_space_end_text = regular_text.rstrip()

print(regular_text)
#'This is a regular text.   '

print(no_space_end_text)
#'This is a regular text.'

Notice that the original regular_text variable remains unchanged, thus you need to assign the return of the method to a new variable, no_space_end_text in this case.

The rstrip() method also accepts specific chars for removal as parameters.

regular_text = "This is a regular text.$@G#"

clean_end_text = regular_text.rstrip("#$@G")

print(regular_text)
#This is a regular text.$@G#

print(clean_end_text)
#This is a regular text.