python中strip怎么使用

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

在Python中,strip()是一个字符串方法,用于删除字符串的开头和结尾的指定字符(默认是空格字符)。

使用方法如下:

  1. 删除字符串开头和结尾的空格字符:
string = "  hello world  "
result = string.strip()
print(result)  # 输出: "hello world"
  1. 删除字符串开头和结尾的指定字符:
string = "!!!hello world!!!"
result = string.strip("!")
print(result)  # 输出: "hello world"
  1. 删除字符串开头和结尾的多个指定字符:
string = "!!!hello world!!!"
result = string.strip("! ")
print(result)  # 输出: "hello world"

注意:

  • strip()方法返回一个新的字符串,原始字符串不会被修改。

  • 如果没有指定参数,默认删除开头和结尾的空格字符。

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

推荐阅读: python中cv2模块的作用是什么