📜  python 从字符串末尾修剪空格 - Python (1)

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

Python 从字符串末尾修剪空格

在Python中,经常需要处理字符串。其中一个常见任务是修剪字符串末尾的空格。下面,我们将介绍如何使用Python从字符串末尾修剪空格。

方法1:使用rstrip()函数

Python提供了一个内置的函数rstrip()来修剪字符串末尾的空格。该函数将从字符串末尾开始扫描,并移除所有空格字符。下面是一个例子:

string = "   hello world  "
trimmed_string = string.rstrip()
print(trimmed_string)

输出结果:

   hello world

我们可以看到,原始字符串中的两个空格被移除了。如果要移除字符串开头的空格,可以使用lstrip()函数;如果要同时移除开头和结尾的空格,可以使用strip()函数。

方法2:使用正则表达式

另一种方法是使用Python中的re模块来使用正则表达式移除末尾的空格。下面是一个例子:

import re

string = "   hello world  "
pattern = r'\s+$'
trimmed_string = re.sub(pattern, '', string)
print(trimmed_string)

输出结果和上面一样:

   hello world

在这个例子中,我们使用了\s表示空格字符,+$表示匹配1个或多个空格字符到字符串末尾。使用re.sub()函数将匹配到的字符串替换为空字符串。

以上就是Python从字符串末尾修剪空格的两种方法。根据情境和个人喜好,可以选择不同的方法。