Python How to trim unnecessary letters from a string

eye-catch Python

Trim is often used when a string contains space at the start/end of the string. How can we trim them in Python?

Sponsored links

Trim space

Python offers strip, rstrip, and lstrip to trim from a string. Why isn’t the name trim?

The behavior looks like this.

text = "   aaaaa bbbb ccc     "
print(f"origin\t [{text}]")          # origin   [   aaaaa bbbb ccc     ]
print(f"rstrip\t [{text.rstrip()}]") # rstrip   [   aaaaa bbbb ccc]
print(f"lstrip\t [{text.lstrip()}]") # lstrip   [aaaaa bbbb ccc     ]
print(f"strip\t [{text.strip()}]")   # strip    [aaaaa bbbb ccc]

All the spaces are cut correctly.

Sponsored links

Trim non-space characters

Sometimes, the characters that we want to remove are not spaces. We can use the same method in this case too.

Let’s remove exclamation marks.

text2 = "! *** Hello World!!"
# print(f"rstrip [{text3.rstrip("!")}]") Error due to double quotations
print(f"rstrip('!')\t [{text2.rstrip('!')}]") # rstrip('!')      [! *** Hello World]
print(f"lstrip('!')\t [{text2.lstrip('!')}]") # lstrip('!')      [ *** Hello World!!]
print(f"strip('!')\t [{text2.strip('!')}]")   # strip('!')       [ *** Hello World]

Even though two characters exist at the end, they are removed as expected.

Note that the double quotes can’t be used. It requires characters but not string.

# this causes an error
strip("!")

Trim multiple characters at once

Perhaps, multiple unnecessary characters could be in the string. Let’s remove them at once.

text2 = "! *** Hello World!!"
print(f"rstrip('* !')\t [{text2.rstrip('* !')}]") # rstrip('* !')    [! *** Hello World]
print(f"lstrip('* !')\t [{text2.lstrip('* !')}]") # lstrip('* !')    [Hello World!!]
print(f"strip('* !')\t [{text2.strip('* !')}]")   # strip('* !')     [Hello World]

The characters are not removed if they are in the middle of the string.

text3 = "! *** Hello ** !! World!!"
print(f"rstrip('* !')\t [{text3.rstrip('* !')}]") # rstrip('* !')    [! *** Hello ** !! World]
print(f"lstrip('* !')\t [{text3.lstrip('* !')}]") # lstrip('* !')    [Hello ** !! World!!]
print(f"strip('* !')\t [{text3.strip('* !')}]")   # strip('* !')     [Hello ** !! World]

Comments

Copied title and URL