[python]rawstring,反斜杠\,reLib-创新互联

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']

创新互联专业为企业提供嘉鱼网站建设、嘉鱼做网站、嘉鱼网站设计、嘉鱼网站制作等企业网站建设、网页设计与制作、嘉鱼企业网站模板建站服务,10余年嘉鱼做网站经验,不只是建网站,更提供有价值的思路和整体网络服务。

第一段:在字符串中,\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识别出结果序列,则反斜杠应重复两次。这很复杂且难以理解,因此强烈建议您使用原始字符串,除了最简单的表达式。

另外有需要云服务器可以了解下创新互联cdcxhl.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。


网页名称:[python]rawstring,反斜杠\,reLib-创新互联
文章URL:http://ybzwz.com/article/dshpsh.html