打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
Python 中的 strip() 方法
userphoto

2024.06.14 河南

关注

Python 中的  strip()  方法用于移除字符串两端的指定字符(默认为空白符,包括空格、换行符  \n 、制表符  \t  等)。 strip()  方法不会改变原始字符串,而是返回一个新的字符串。

以下是  strip()  方法的一些用法示例:

移除字符串两端的空白符:

s = "  Hello World!  "

stripped = s.strip()

print(stripped)  # 输出: "Hello World!"

移除字符串两端的特定字符: 你可以指定一个字符序列作为参数, strip()  方法将移除字符串两端的所有这些字符。

s = "----Hello World!----"

stripped = s.strip('-')

print(stripped)  # 输出: "Hello World!"

移除字符串两端的多种字符: 如果指定的字符序列中包含多种字符, strip()  方法将移除字符串两端的这些字符。

s = "abcHello World!cba"

stripped = s.strip('abc')

print(stripped)  # 输出: "Hello World!"

不移除字符串中间的字符:  strip()  只会移除字符串两端的字符,不会影响字符串中间的字符。

s = "abc  Hello World!  abc"

stripped = s.strip()

print(stripped)  # 输出: "  Hello World!  "

对列表中的每个字符串使用  strip() : 如果你想对列表中的每个字符串元素使用  strip() ,你可以使用列表推导式。

list_of_strings = ["  item1 ", " item2 ", "item3 "]

stripped_list = [s.strip() for s in list_of_strings]

print(stripped_list)  # 输出: ['item1', 'item2', 'item3']

 strip()  方法的变体还包括  lstrip()  和  rstrip() ,分别用于移除字符串左端和右端的字符。

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
Python中去除字符串两端空格的方法!
在 Python 中从列表中删除换行符的多种方法
在Python中正则这样玩,通过两个例子,让你喜欢上正则
9.Python从入门到精通—Python 字符串格式化,三引号,Unicode 字符串
Python转义字符及用法
Python 字符串方法详解
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服