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

Python Basic Tutorial

Python Flow Control

Python Functions

Python Data Types

Python File Operations

Python Objects and Classes

Python Date and Time

Advanced Knowledge of Python

Python Reference Manual

Python string strip() usage and example

Python string methods

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

strip() deletes characters from both ends of the string based on the parameter (a string specifying the set of characters to be removed).

strip() syntax is:

string.strip([chars])

strip() parameters

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

If chars is not provided as a parameter, 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 spaces
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

Python string methods