《python_cookbook》字符串和文本

  1. 分割字符串
    使用re.split(pattern,string),通过正则表达式可以指定多个分隔符,如果正则包含了了括号捕获分组,分隔符也会出现在结果中,re.split也可以用来重新构造新字符串
import re
line='abd abs;asd ass,g  g'

res1=re.split(r'[;,\s]\s*',line)
fileds=re.split(r'(\s|;|,)',line)
value=fileds[::2]
tag=fileds[1::2]
#重新构造字符串
new_line=''.join(v+d for v,d in zip(value,tag))
print(res1)
print(new_line)
  1. 字符串开头或者结尾匹配
    str.startswith()
    str.endswith()
    str[start:final:step]

  2. shell部分回去实验

  3. 字符串匹配、搜索、替换
    搜索:str.find()以及第2条前两个方法
    匹配:pattern.match(str)、pattern.findall(str)
    pattern想要多次复用就可以采用pattern=re.compile(r’正则’)
    这一点和js的区别是js是str.match(pattern)而python是pattern.match(str),而且js的正则需要注意转义的问题,python只需要r’(\d+)(\d+)’,当然也可以像js那样用反斜杠/*
    替换:str.replace(oldstr,newstr)这一点和js的区别是js支持正则,python的replace不支持
    re.sub()非常好用
    多行匹配
    *’.’**不能匹配换行符,因此可以将换行符加入到模式中

comp='/*注释' \
     'fff*/'
comment=re.compile(r'/\*((?:.|\n)*?)\*/')
print(comment.findall(comp))
  1. 删除字符串中开头结尾或者中间不想要的字符str.strip()
    application审查清理文本字符串:

  2. 处理html和xml, html和xml包
    处理<: html.escape(str)

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值