溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶(hù)服務(wù)條款》

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

發(fā)布時(shí)間:2020-08-02 07:44:27 來(lái)源:網(wǎng)絡(luò) 閱讀:198 作者:wx5a4df9dc5cd9d 欄目:編程語(yǔ)言
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á)式。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI