温馨提示×

Python怎么去除字符串首尾空格

小亿
137
2023-09-25 09:44:28
栏目: 编程语言
Python开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

可以使用strip()方法来去除字符串首尾的空格。

示例代码如下:

string = "  hello world  "
new_string = string.strip()
print(new_string)  # 输出结果为"hello world"

strip()方法可以去除字符串首尾的空格,并返回一个新的字符串。如果想去除字符串中间的空格,可以使用replace()方法将空格替换为空字符串,示例如下:

string = "  hello   world  "
new_string = string.replace(" ", "")
print(new_string)  # 输出结果为"helloworld"

另外,如果只想去除字符串开头的空格,可以使用lstrip()方法;如果只想去除字符串末尾的空格,可以使用rstrip()方法。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:python怎么去除字符串前后空格

0