How to remove leading and trailing whitespace from a string in Python

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

To remove leading and trailing whitespace from a string in Python, you can use the strip() method. Here’s an example:

my_string = "  Hello, World!  "
stripped_string = my_string.strip()
print(stripped_string)

This will output Hello, World!, with the leading and trailing whitespace removed.

You can also use the lstrip() method to remove only leading whitespace, or the rstrip() method to remove only trailing whitespace.

# Remove leading whitespace only
my_string = "  Hello, World!  "
left_stripped_string = my_string.lstrip()
print(left_stripped_string)

# Remove trailing whitespace only
my_string = "  Hello, World!  "
right_stripped_string = my_string.rstrip()
print(right_stripped_string)

These will output Hello, World! and Hello, World! respectively, with the appropriate whitespace characters removed.

Tags:

related content