资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

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

创新互联成立与2013年,先为涿鹿等服务建站,涿鹿等地企业,进行企业商务咨询服务。为涿鹿企业网站制作PC+手机+微官网三网同步一站式服务解决您的所有建站问题。

第一段:在字符串中,\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 stringsfor all but the simplest expressions.
如果你没有使用原始字符串来表达模式,请记住Python也使用反斜杠作为字符串文字中的转义序列; 如果Python的解析器无法识别转义序列,则反斜杠和后续字符将包含在结果字符串中。但是,如果Python识别出结果序列,则反斜杠应重复两次。这很复杂且难以理解,因此强烈建议您使用原始字符串,除了最简单的表达式。


网站名称:[python]rawstring,反斜杠\,reLib
文章位置:http://cdkjz.cn/article/jijhgp.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

大客户专线   成都:13518219792   座机:028-86922220