温馨提示×

python的strip函数怎么使用

小亿
84
2023-12-21 06:31:10
栏目: 编程语言

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(‘-’)函数去除了字符串首尾的连续的"-"字符。

0