新聞中心
import re
print('\ a:{}個(gè)字符,\\a:{}個(gè)字符'.format(len('\ a'),len('\a')))
#結(jié)果: \ a:3個(gè)字符,\a:1個(gè)字符
match2 = re.findall('\\\\','\ a')
match3 = re.findall('\\\\','\a')
match4 = re.findall('\\a','\a')
print(match2,match3,match4)
print(match2[0],match4[0])
#結(jié)果: ['\\'] [] ['\x07']
#結(jié)果: \
match5 = re.findall(r'\\','\ a')
match6 = re.findall(r'\\','\a')
match7 = re.findall(r'\a','\a')
print(match5,match6,match7)
#結(jié)果: ['\\'] [] ['\x07']
?
第一段:在字符串中,\a為一個(gè)字符,\空格為兩個(gè)字符。
?
第二段:在字符串中,無(wú)法搜索出\a字符中單獨(dú)的反斜杠\,需要整體字符搜索。當(dāng)需要搜索單獨(dú)的一個(gè)反斜杠\時(shí),需要使用兩個(gè)\來(lái)搜索,即使用一個(gè)轉(zhuǎn)義符\來(lái)表示反斜杠本身,re中pattern則要寫(xiě)為'\\\\'或r'\\'。
?
第三段:r'\'相當(dāng)于'\\',同理r'\\'相當(dāng)于"\\\\"。
?
參考: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.
如果你沒(méi)有使用原始字符串來(lái)表達(dá)模式,請(qǐng)記住Python也使用反斜杠作為字符串文字中的轉(zhuǎn)義序列; 如果Python的解析器無(wú)法識(shí)別轉(zhuǎn)義序列,則反斜杠和后續(xù)字符將包含在結(jié)果字符串中。但是,如果Python識(shí)別出結(jié)果序列,則反斜杠應(yīng)重復(fù)兩次。這很復(fù)雜且難以理解,因此強(qiáng)烈建議您使用原始字符串,除了最簡(jiǎn)單的表達(dá)式。
另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)cdcxhl.cn,海內(nèi)外云服務(wù)器15元起步,三天無(wú)理由+7*72小時(shí)售后在線,公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國(guó)服務(wù)器、虛擬主機(jī)、免備案服務(wù)器”等云主機(jī)租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡(jiǎn)單易用、服務(wù)可用性高、性價(jià)比高”等特點(diǎn)與優(yōu)勢(shì),專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應(yīng)用場(chǎng)景需求。
標(biāo)題名稱:[python]rawstring,反斜杠\,reLib-創(chuàng)新互聯(lián)
本文來(lái)源:http://www.dlmjj.cn/article/dshpsh.html