温馨提示×

python中怎么用strip函数去掉符号

小亿
100
2023-11-23 02:52:39
栏目: 编程语言

在Python中,可以使用strip()函数去掉字符串前后的指定字符。strip()函数的语法如下:

string.strip([characters])

其中,string是要处理的字符串,characters是可选参数,用于指定要去掉的字符。如果不提供characters参数,strip()函数默认会去掉字符串前后的空格。

下面是一些使用strip()函数去掉符号的示例:

string = "Hello World!"
new_string = string.strip("!")  # 去掉字符串前后的感叹号
print(new_string)  # 输出:Hello World

string = "$$Python is awesome$$"
new_string = string.strip("$")  # 去掉字符串前后的美元符号
print(new_string)  # 输出:Python is awesome

需要注意的是,strip()函数只会去掉字符串前后的指定字符,不会去掉字符串中间的字符。如果需要去掉字符串中间的指定字符,可以考虑使用replace()函数或正则表达式来实现。

0