深度阅读

How to trim a string in Python

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

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.

博客作者

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