How to Use String strip() Method in PythonPython Basics


The strip() method removes spaces or a sequence of characters at the beginning and end of a string.

Example

#!/usr/bin/python3
# -*- coding: UTF-8 -*-

# strip at the beginning
str = "ABCabcABCD"
print(str, ' -> ', str.strip('ABC'))

# strip at the beginning and end
str = "ABCabcABC"
print(str, ' -> ', str.strip('ABC'))

# strip spaces at the beginning and end
str = " ABCabcABC "
print(str ,' -> ', str.strip())

Output:

ABCabcABCD  ->  abcABCD
ABCabcABC  ->  abc
 ABCabcABC   ->  ABCabcABC

Syntax

string.strip([x])

Parameters

Name Description
x A string specifying the set of characters to be removed

Return Value

It returns a new string generated by removing the sequence of characters specified at the beginning and end of the string.

© 2024 Learnwithgpt.org, all rights reserved. Privacy Policy | Contact Us