06.0 Python‎ > ‎Python Notes‎ > ‎String Processing‎ > ‎

.strip(), .lstrip(), .rstrip()

.strip(), .lstrip(), .rstrip()

Will return the value of a string variable with leading and trailing characters removed.
Default, removes whitespace (spaces). If a character is supplied, that character will be removed.

.strip()
: will remove leading and trailing characters
.lstrip():  will remove leading characters
.rstrip(): will remove trailing characters

.strip(), .lstrip(), .rstrip() Syntax

new_variable = original_variable.strip(chr)
new_variable = original_variable.lstrip(chr)
new_variable = original_variable.rstrip(chr)

chr: a string of characters to be removed
original_variable:  the original variable 
new_variable: will contain the modified string 

.strip(), .lstrip(), .rstrip() Examples

To remove the EOL character from the right side of a string:

    line = line.rstrip('\n')

To remove leading and trailing whitespace (spaces)
data = "     hello there    "
data = data.strip()

To remove the "," character from the right side of a string:

    name = name.rstrip(',')

Code:
    str ="mississippim"
    print(str.strip('m'))
    print(str.rstrip('m'))
    print(str.lstrip('m'))
    print(str.strip('m'))
    print (str)

Output:
ississippi
mississippi
ississippim
ississippi
mississippim

notice the original string str is not changed


Comments