温馨提示×

python strip函数怎么使用

小亿
118
2023-09-26 01:12:39
栏目: 编程语言
Python开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

strip函数可以用来移除字符串的头尾指定字符,默认移除字符串两端的空格或换行符。

基本用法:

string.strip([chars])

其中,string表示要操作的字符串,chars表示要移除的字符集合。如果不指定chars参数,默认移除字符串两端的空格或换行符。

示例:

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

如果要移除字符串中指定的字符,可以通过传入chars参数来实现。

示例:

string = "hello world"
new_string = string.strip("hld")
print(new_string)  # 输出:ello wor

在上面的示例中,strip函数移除了字符串"hello world"中的字符"h""l""d"

另外,还有lstrip函数和rstrip函数分别用于移除字符串左侧和右侧的指定字符。用法与strip函数类似。

更多用法可以参考Python官方文档:https://docs.python.org/3/library/stdtypes.html#str.strip

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

推荐阅读:python strip函数如何使用

0