python中str.strip()怎么使用

600
2023/9/25 13:21:39
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

str.strip()方法用于去除字符串首尾指定字符,默认去除空格。

使用方法如下:

str.strip([chars])

其中,chars为可选参数,用于指定需要去除的字符。

示例:

s = "  hello world  "
print(s.strip())  # 输出:"hello world"
s = "  hello world  "
print(s.strip(" "))  # 输出:"hello world"
s = "#hello world#"
print(s.strip("#"))  # 输出:"hello world"

请注意,str.strip()方法只能去除字符串首尾的指定字符,中间部分不会被去除。如果需要去除字符串中所有指定字符,可以使用str.replace()方法。

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

推荐阅读: python中怎么用replace替换多个字符