深度阅读

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

作者
作者
2023年08月22日
更新时间
8.53 分钟
阅读时间
0
阅读量

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.

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。