📌  相关文章
📜  python 从字符串末尾删除空格 - Python (1)

📅  最后修改于: 2023-12-03 15:04:14.795000             🧑  作者: Mango

Python 从字符串末尾删除空格

在 Python 中,要从字符串末尾删除空格,可以使用 rstrip() 方法。

介绍

Python 的 rstrip() 方法是用来从字符串末尾删除指定字符,默认是删除空格。它返回一个新字符串,不会修改原来的字符串。

例如:

s = 'Python       '
s = s.rstrip()
print(s)

以上代码的输出结果是 Python,末尾的多余空格已经被删除了。

示例

下面这个例子演示了如何从多行字符串中删除每行末尾的空格:

s = '''First line     
Second line   
Third line      '''

new_s = '\n'.join([line.rstrip() for line in s.split('\n')])

print(new_s)

输出:

First line
Second line
Third line
注意事项

使用 rstrip() 方法时要注意,它只删除末尾的空格,而不会删除开头的空格或中间的空格。如果需要删除其他位置的空格,可以使用 lstrip() 方法或 strip() 方法,它们分别用来删除开头和末尾的空格。

s = '    Python   '
s = s.strip()
print(s)

以上代码的输出结果是 Python,开头和末尾的空格都被删除了。

结论

使用 rstrip() 方法可以方便地删除字符串末尾的空格,提高程序的效率和可读性。同时也要注意使用场景,避免出现不必要的错误。