在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()
函数或正则表达式来实现。
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: Python脚本索引越界问题怎么解决