How to remove spaces at both ends of a string using Python
This article describes how to remove spaces at both ends of a string in Python. This article describes how to use string. lstrip, string. rstrip, string. strip, and other functions. For more information, see
Purpose
Returns a string with no leading or trailing spaces.
Method
You can use the following methods of string processing:
String. lstrip (s [, chars])
Return a copy of the string with leading characters removed. if chars is omitted or None, whitespace characters are removed. if given and not None, chars must be a string; the characters in the string will be stripped from the beginning of the string this method is called on.
String. rstrip (s [, chars])
Return a copy of the string with trailing characters removed. if chars is omitted or None, whitespace characters are removed. if given and not None, chars must be a string; the characters in the string will be stripped from the end of the string this method is called on.
String. strip (s [, chars])
Return a copy of the string with leading and trailing characters removed. if chars is omitted or None, whitespace characters are removed. if given and not None, chars must be a string; the characters in the string will be stripped from the both ends of the string this method is called on.
The specific effect is as follows:
The Code is as follows:
In [10]: x = 'Hi, Jack! '
In [11]: print '|', x. lstrip (), '|', x. rstrip (), '|', x. strip (), '|'
| Hi, Jack! | Hi, Jack! | Hi, Jack! |
The chars parameter is used to delete a specific symbol. Note that spaces are not removed. For example:
The Code is as follows:
In [12]: x = 'xyxyxxxyy Hello xyxyxyxyy'
In [13]: print x. strip ('xy ')
Hello