python strip()函数怎么使用

2348
2023/9/8 3:52:59
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

Python中的strip()函数是用来删除字符串中的指定字符,默认情况下是删除字符串两端的空格或换行符。

可以使用以下语法来使用strip()函数:

string.strip([chars])

其中,string表示要操作的字符串,[chars]是可选参数,用来指定要删除的字符。如果不指定chars,则默认删除字符串两端的空格或换行符。

以下是一些使用strip()函数的示例:

示例1:删除字符串两端的空格

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

示例2:删除字符串两端的特定字符

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

示例3:删除字符串两端的换行符

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

需要注意的是,strip()函数不会修改原始字符串,而是返回一个新的字符串。

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

推荐阅读: python怎么爬取网页内的指定内容