扫描二维码下载沐宇APP

沐宇

微信扫码使用沐宇小程序

沐宇

python的strip函数怎么使用

扬州沐宇科技
2023-12-21 06:31:10
python

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

函数语法:strip([chars])

其中,chars参数是可选的,用于指定要去除的字符。如果没有指定chars参数,则默认去除字符串首尾的空格字符。

示例:

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

string = "-----hello, world!-----"
new_string = string.strip('-')
print(new_string)   # 输出:hello, world!

在第一个示例中,strip()函数去除了字符串首尾的空格字符。

在第二个示例中,strip(‘-’)函数去除了字符串首尾的连续的"-"字符。

扫码添加客服微信