How to trim a string in Python

Published on Aug. 22, 2023, 12:16 p.m.

To trim a string in Python, you can use the strip() method, which removes whitespace characters from both the beginning and end of the string. Here’s an example:

my_string = "   Hello world!   "
trimmed_string = my_string.strip()

print(trimmed_string)

In this example, my_string has leading and trailing whitespace characters, while trimmed_string is a new string that has the same content but with the leading and trailing whitespace removed. The code uses the strip() method without arguments to trim the string.

You can also use the lstrip() and rstrip() methods to trim only the leading or trailing whitespace characters, respectively.

my_string = "   Hello world!   "
left_trimmed = my_string.lstrip()
right_trimmed = my_string.rstrip()

print(left_trimmed)
print(right_trimmed)

This will output “Hello world! ” for left_trimmed and ” Hello world!” for right_trimmed.

If you need to remove specific characters from only the beginning or end of the string, you can pass them as an argument to lstrip() or rstrip().

my_string = ">>> Hello world! <<<"
left_trimmed = my_string.lstrip('>')
right_trimmed = my_string.rstrip('<')

print(left_trimmed)
print(right_trimmed)

This will output ” Hello world! <<<” for left_trimmed and “>>> Hello world! ” for right_trimmed.

Tags:

related content