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

Use the strip() method to remove spaces from the beginning and the end of a string.

regular_text = "  This is a regular text.   "

no_space_text = regular_text.strip()

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

print(no_space_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_text in this case.

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

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

clean_text = regular_text.strip("AbC#$@G")

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

print(clean_text)
#This is a regular text.