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

发布时间:2020-08-02 07:44:27 作者:wx5a4df9dc5cd9d
来源:网络 阅读:195
import re
print('\ a:{}个字符,\\a:{}个字符'.format(len('\ a'),len('\a')))
#结果:  \ a:3个字符,\a:1个字符

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

match5 = re.findall(r'\\','\ a')
match6 = re.findall(r'\\','\a')
match7 = re.findall(r'\a','\a')
print(match5,match6,match7)
#结果:  ['\\'] [] ['\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识别出结果序列,则反斜杠应重复两次。这很复杂且难以理解,因此强烈建议您使用原始字符串,除了最简单的表达式。

推荐阅读:
  1. python3 实现口罩抽签的功能
  2. 利用Python实现在同一网络中的本地文件共享方法

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python re lib strin

上一篇: windows环境下安装npm、cnpm、bower

下一篇:兄弟们,请求支援,怎么实现互通,全部都互通的

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》