[python] raw string,反斜杠\,re Lib

import re
print('\ a:{}个字符,\\a:{}个字符'.format(len('\ a'),len('\a')))
#结果:  \ a:3个字符,\a:1个字符

match1 = re.findall('\\\\','\ a')
match2 = re.findall('\\\\','\a')
match3 = re.findall('\\a','\a')
print(match1,match2,match3)
print(match1[0],match3[0])
#结果:  ['\\'] [] ['\x07']
#结果:  \ 

match4 = re.findall(r'\\','\ a')
match5 = re.findall(r'\\','\a')
match6 = re.findall(r'\a','\a')
print(match4,match5,match6)
#结果:  ['\\'] [] ['\x07']

第一段:在字符串中,\a为一个字符,\空格为两个字符。

第二段:在字符串中,无法搜索出\a字符中单独的反斜杠\,需要整体字符搜索。当需要搜索单独的一个反斜杠\时,需要使用两个\来搜索,即使用一个转义符\来表示反斜杠本身,re中pattern则要写为 “\\\\” 或 r"\\"。

第三段:r"\" 相当于 “\\”,同理 r"\\" 相当于 “\\\\”。

参考:https://docs.python.org/3/library/re.html#regular-expression-syntax

\

If you’re not using a raw string to express the pattern, remember that Python also uses the backslash as an escape sequence in string literals; if the escape sequence isn’t recognized by Python’s parser, the backslash and subsequent character are included in the resulting string. However, if Python would recognize the resulting sequence, the backslash should be repeated twice. This is complicated and hard to understand, so it’s highly recommended that you use raw strings for all but the simplest expressions.
如果你没有使用原始字符串来表达模式,请记住Python也使用反斜杠作为字符串文字中的转义序列; 如果Python的解析器无法识别转义序列,则反斜杠和后续字符将包含在结果字符串中。但是,如果Python识别出结果序列,则反斜杠应重复两次。这很复杂且难以理解,因此强烈建议您使用原始字符串,除了最简单的表达式。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值