python中的字符串strip()、split()和re.split()的用法

一、strip()用法

用于移除字符串首尾指定的字符
如果strip()括号里为空,即未指定要删除的字符,默认删除字符串首尾的空格和换行符

输入

str = "   The weather is bright and warm\n"
print("1.", str)
print("2", str.strip())

输出

1.    The weather is bright and warm

2 The weather is bright and warm

二、split()用法

用于指定分隔符对字符串进行切片
如果split()括号内为空,未指定要分割的字符串,默认是按照空格进行分割,返回一个字符串列表

输入

str = "   The weather is bright and warm\n"
print("1.", str)
print("2.", str.split())
print("3.", str.split("e"))

输出

1.    The weather is bright and warm

2. ['The', 'weather', 'is', 'bright', 'and', 'warm']
3. ['   Th', ' w', 'ath', 'r is bright and warm\n']

三、re.split()用法

split不支持同时使用多种字符做分隔符,如果想实现这样的效果,可以用re

输入

import re

str = "   [The weather], is bright and warm!"
print("1.", str)
print("2.", re.split("[\[\],!]", str))

输出

1.    [The weather], is bright and warm!
2. ['   ', 'The weather', '', ' is bright and warm', '']
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值