[Edit, test and edit] zero-based learning python_04_string (delete blanks)

Remove white space in the string:

In the program, the extra white space can be confusing. To the programmer,'python' and'python' look almost the same, but to the program, they are two different strings. Python can find the extra whitespace in'python' and think it is meaningful - unless you tell it that it is not. White space is important because you often need to compare whether two strings are the same. For example, an important example is checking a user's username when logging in to a website. But in some much simpler situations, the extra spaces can also be confusing.

Fortunately, in Python, deleting the extra whitespace in the data entered by the user is easy.

Python can find extra whitespace at the beginning and end of a string. To ensure that there are no blanks at the end of the string, use the method rstrip().
[Edit, test and edit] zero-based learning python_04_string (delete blanks)

favorite_teacher ='Qingyun'+' Sharp Sword'
print(favorite_teacher)
favorite_teacher ='Qingyun'.rstrip()+'Sharp Sword'
print(favorite_teacher)

The string stored in the variable favorite_teacher contains extra white space at the end. When you print the value of this variable, you can see the trailing space. After calling the method rstrip() on the string "Qingyun", this extra space is deleted.

You can also remove the blanks at the beginning of the string, using the method lstrip()

favorite_teacher ='Qingyun' + 'Sharp Sword'
print(favorite_teacher)
favorite_teacher ='Qingyun'+' Sharp Sword'.lstrip()
print(favorite_teacher) The
execution result is as follows, at a glance:

[Edit, test and edit] zero-based learning python_04_string (delete blanks)

Remove the blanks at both ends of the string at the same time, use the method strip()

Directly on the sample code:

favorite_teacher ='Qingyun'+'Sharp Sword'+'Blade'
print(favorite_teacher)
favorite_teacher ='Qingyun'+'Sharp Sword'.strip()+'Blade'
print(favorite_teacher) The
execution result of print(favorite_teacher) is as follows:

[Edit, test and edit] zero-based learning python_04_string (delete blanks)

Guess you like

Origin blog.51cto.com/14972695/2550601