3 3原始字串

2021-08-14 15:05:18 字數 888 閱讀 2824

聽起來好像反斜槓是乙個好東西,但不妨試試列印c:\now:

>>> string = 'c:\now'

>>> string

'c:\now'

>>> print(string)

c:ow

>>>

列印結果並不是我們預期的,原因是

反斜槓(\)和後邊的字元(n)恰好構成了換行符(\n)。這時有朋友會說:「

用反斜槓來轉義反斜槓不就可以了嗎?」不錯,可以這樣來做:

>>> string = 'c:\\now'

>>> string

'c:\\now'

>>> print(string)

c:\now

>>>

但是如果乙個

字串裡面有很多個反斜槓的時候這樣就很不安逸了。不過還是有快捷的方法的,那就是

使用原始字串。原始字串的使用非常簡單,只需要

>>> string = r'c:\now'

>>> string

'c:\\now'

>>> print(string)

c:\now

>>>

注意:無論是否原始字串,都不能以反斜槓作為結尾(反斜槓在字串末尾表示該字串還沒有結束,還行繼續的意思):

>>> string = 'fishc\'

syntaxerror: eol while scanning string literal

>>> string = r'fishc\'

syntaxerror: eol while scanning string literal

>>>

python原始字串

那麼,我們如何設計程式來處理任意數量的時差?答案是 使用萬用字元 wildcard urlpatterns 正如我們之前提到過,乙個url模式就是乙個正規表示式。因此,這裡可以使用d 來匹配1個以上的數字。4urlpatterns patterns r time plus d hours ahead...

原始字串 Unicode

原始字串以r開頭,可以在原始字串中放入任何字元,但不能以反斜線 結尾,用來防止反斜線轉義!在普通字串中,反斜線 會轉義,在字串中通常不能直接加入的內容。如 print c nowhere c owhere要輸出c nowhere,必須加反斜槓轉義。print c nowhere c nowhere ...

python 原始字串

prthon 反斜槓為轉義字元 str c now str c now print str syntaxerror invalid character u ff09 print c noe c oe 字串前加 r 為原始字元 str r c now a str c now a print str c...