English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Python basic tutorial

Python flow control

Fonctions en Python

Types de données en Python

Python file operations

Objects and classes in Python

Python date and time

Advanced knowledge of Python

Python Reference Manual

Usage and examples of Python string strip()

String methods in Python

strip() method returns a copy of the string used to remove the specified characters (or character sequence) at the beginning and end of the string (the default is spaces or newline characters).
Note: This method can only delete characters at the beginning or end, and cannot delete characters in the middle.

strip() removes characters from both sides of the string based on the parameter (a string specifying the set of characters to be deleted).

The syntax of strip() is:

string.strip([chars])

strip() parameters

  • chars (optional)-A string that specifies the set of characters to be removed.

If the chars parameter is not provided, all leading and trailing spaces will be removed from the string.

strip() return value

strip() returns a copy of the string with leading and trailing characters removed.

  • When the character combination in the chars parameter does not match the characters on the left side of the string, it will stop deleting leading characters.

  • Similarly, when the character combination in the chars parameter does not match the characters on the right side of the string, it will stop deleting trailing characters.

Example: the working of strip()

string = ' xoxo love xoxo   '
# Remove leading white space
print(string.strip())
print(string.strip(' xoxoe'))
# The parameter does not contain spaces
# Do not delete any characters.
print(string.strip('sti'))
string = 'android is awesome'
print(string.strip('an'))

When running the program, the output is:

xoxo love xoxo
lov
 xoxo love xoxo   
droid is awesome

String methods in Python