When the user enters data, it is likely that he or she may inadvertently enter extra spaces, or in some
scenarios, spaces and special characters are not allowed before and after the character string.
At this time, spaces and special characters in the string need to be removed.
The special characters here refer to the:
carriage return (\r)
line feed (\n), and so on
In Python, string variables provide three ways to remove extra spaces and special characters in a string.
strip(): Removes spaces or special characters before and after (left and right) strings.
lstrip(): Removes spaces or special characters in front of (left) the string.
rstrip(): Removes spaces or special characters after the string (on the right).
Note that Python's str is immutable (meaning immutable means that once the string is formed, the sequence of
characters it contains cannot change in any way), so these three methods just return that the white space
before or after the string is removed Subsequent copies do not change the string itself.
Python Strip Function
The strip function is used to remove left and right spaces and special characters. The syntax of
this function is:
Among them, str represents the original string, [chars] is used to specify the characters to be deleted,
and multiple characters can be specified at the same time. If not specified manually, spaces and
special characters such as tabs, carriage returns, and line feeds will be deleted by default.
string = "www.freelearningpoints.com\t\n\r"
string.strip() #remove special characters by default
It is not difficult to analyse the results of the analysis. Strip () can indeed remove the spaces and
special characters on the left and right sides of the string but does not really change the string itself.
Python lstrip Function
The lstrip () method is used to strip spaces and special characters left side of string. The syntax of the
function is as follows:
The meaning of the str and chars parameters is exactly the same as str and chars in the strip() syntax,