Python 跳脫字元



跳脫字元

跳脫字元是由反斜槓 ( \ ) 後跟一個字元組成的字元。它告訴直譯器 此跳脫字元(序列)具有特殊含義。例如,\n 是一個表示換行的轉義序列。當 Python 在字串中遇到此序列時,它會理解需要換行。

除非存在 "r" 或 "R" 字首,否則字串和位元組字面量中的轉義序列將根據與標準 C 使用的規則類似的規則進行解釋。在 Python 中,如果在引號符號之前新增 "r" 或 "R" 字首,則字串 將成為原始字串。因此,'Hello' 是普通字串,而 r'Hello' 是原始字串。

示例

在下面的示例中,我們實際演示了原始字串和普通字串。

# normal string
normal = "Hello"
print (normal)

# raw string
raw = r"Hello"
print (raw)

上述程式碼的輸出如下所示:

Hello
Hello

在正常情況下,兩者之間沒有區別。但是,當跳脫字元嵌入到字串中時,普通字串實際上會解釋轉義序列,而原始字串不會處理跳脫字元。

示例

在下面的示例中,當列印普通字串時,跳脫字元 '\n' 被處理以引入換行符。但是,由於原始字串運算子 'r',跳脫字元的效果不會根據其含義進行轉換。

normal = "Hello\nWorld"
print (normal)

raw = r"Hello\nWorld"
print (raw)

執行上述程式碼後,將列印以下結果:

Hello
World
Hello\nWorld

Python 中的跳脫字元

下表顯示了 Python 中使用的不同跳脫字元:

序號 轉義序列及含義
1

\<newline>

反斜槓和換行符被忽略

2

\\

反斜槓 (\)

3

\'

單引號 (')

4

\"

雙引號 (")

5

\a

ASCII 響鈴 (BEL)

6

\b

ASCII 退格 (BS)

7

\f

ASCII 換頁 (FF)

8

\n

ASCII 換行 (LF)

9

\r

ASCII 回車 (CR)

10

\t

ASCII 水平製表符 (TAB)

11

\v

ASCII 垂直製表符 (VT)

12

\ooo

具有八進位制值 ooo 的字元

13

\xhh

具有十六進位制值 hh 的字元

跳脫字元示例

以下程式碼顯示了上表中列出的轉義序列的用法:

# ignore \
s = 'This string will not include \
backslashes or newline characters.'
print (s)

# escape backslash
s=s = 'The \\character is called backslash'
print (s)

# escape single quote
s='Hello \'Python\''
print (s)

# escape double quote
s="Hello \"Python\""
print (s)

# escape \b to generate ASCII backspace
s='Hel\blo'
print (s)

# ASCII Bell character
s='Hello\a'
print (s)

# newline
s='Hello\nPython'
print (s)

# Horizontal tab
s='Hello\tPython'
print (s)

# form feed
s= "hello\fworld"
print (s)

# Octal notation
s="\101"
print(s)

# Hexadecimal notation
s="\x41"
print (s)

它將產生以下輸出

This string will not include backslashes or newline characters.
The \character is called backslash
Hello 'Python'
Hello "Python"
Helo
Hello
Hello
Python
Hello Python
hello
world
A
A
廣告