python中的strip函数怎么用

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

在Python中,strip函数用于去除字符串首尾的指定字符(默认为空格字符)。

strip函数的语法如下:

string.strip([chars])

参数说明:

  • chars(可选):指定要去除的字符。如果不指定,则默认去除字符串首尾的空格字符。

示例:

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

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

string = "123hello world321"
print(string.strip("123"))  # 输出: "hello world"

在上面的示例中,第一个例子是去除字符串string首尾的空格字符。第二个例子是去除字符串string首尾的连续的-字符。第三个例子是去除字符串string首尾的连续的123字符。

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

推荐阅读: python多线程和多进程的区别是什么