Strips leading and trailing characters
Usage
The strip()
method removes whitespace from the beginning (leading) and end (trailing) of the string by default.
By adding chars parameter, you can also specify the characters you want to strip.
Syntax
string.strip(chars)
Parameter | Condition | Description |
chars | optional | A list of characters to be removed from the string |
Return Value
The method return a copy of the string with the leading and trailing characters removed.
Strip Whitespace
By default, the method removes leading and trailing whitespace.
S = ' Hello, World! '
x = S.strip()
print(x)
# Prints Hello, World!
Newline '\n'
, tab '\t'
and carriage return '\r'
are also considered as whitespace characters.
S = ' \t Hello, World! \n\r '
x = S.strip()
print(x)
# Prints Hello, World!
Strip Characters
By adding chars parameter, you can also specify the character you want to strip.
# Strip single character 'a'
S = 'aaabaaaa'
x = S.strip('a')
print(x)
# Prints b
Strip Multiple Characters
The chars parameter is not a prefix or suffix; rather, all combinations of its values are stripped.
In below example, strip()
would strip all the characters provided in the argument i.e. ‘c’, ‘m’, ‘o’, ‘w’, ‘z’ and ‘.’
S = 'www.example.com'
x = S.strip('cmowz.')
print(x)
# Prints example
More About strip() Method
Characters are removed from both ends until reaching a string character that is not contained in the set of characters in chars.
S = 'xxxxSxxxxSxxxx'
x = S.strip('x')
print(x)
# Prints SxxxxS
Here is another example:
S = '... - Version 3.2 Model-32 ...'
x = S.strip('.- ')
print(x)
# Prints Version 3.2 Model-32