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:
In Python, string variables provide three ways to remove extra spaces and special characters in a string. These are:
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.
The strip function is used to remove left and right spaces and special characters. The syntax of this function is:
str.strip([chars])
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.
[Example:]
string = "www.freelearningpoints.com\t\n\r" string.strip() #remove special characters by default string.strip(“,\r”)
The output is:
'www.freelearningpoints.com'
'www.freelearningpoints.com\t\n'
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.
The lstrip () method is used to strip spaces and special characters left side of string. The syntax of the function is as follows:
str.lstrip([chars])
The meaning of the str and chars parameters is exactly the same as str and chars in the strip() syntax, respectively.
[Example:]
string = "www.freelearningpoints.com\t\n\r" string.lstrip()
The output is:
'www.freelearningpoints.com\t\n\r'
The rstrip() function is used to remove spaces and special characters on the right side of a string. Its syntax is:
str.rstrip([chars])
[Example:]
string = "www.freelearningpoints.com\t\n\r" string.rstrip()
The output is:
'www.freelearningpoints.com'
More Tutorials:
Python Installation - Linux (Ubuntu)More Python Exercises:
Python String Exercises