如何在 Python 中處理字串中的轉義序列?


在 Python 中,轉義序列是用於表示某些難以鍵入或列印的特殊字元的特殊字元。它們通常由反斜槓 (\) 後跟表示特殊序列的字元表示。例如,換行符 (\n) 用於在字串中表示換行。以下是 Python 中使用的一些常見轉義序列

\n: 換行符

\t: 製表符

': 單引號字元

": 雙引號字元

在 Python 中,我們可以使用反斜槓 (\) 後跟字元或字元組合來處理字串中的轉義序列。以下是一些帶有逐步說明的程式碼示例

使用轉義序列在字串中包含特殊字元

示例

在 string1 中,雙引號使用轉義序列 " 包含。在 string2 中,反斜槓使用轉義序列 \\ 包含。

# include a double quote in a string using escape sequence
string1 = "He said, "Hello World!""
# include a backslash in a string using escape sequence
string2 = "C:\\Users\\Documents\\file.txt"
print(string1)
print(string2)

輸出

He said, "Hello World!"
C:\Users\Documents\file.txt

使用原始字串格式忽略轉義序列

示例

字串前面的 r 告訴 Python 使用原始字串格式,該格式會忽略轉義序列。

# using the raw string format to ignore escape sequences
string = r'C:\Users\Documents\file.txt'
print(string)

輸出

C:\Users\Documents\file.txt

使用 replace() 方法將轉義序列替換為其實際字元

示例

replace() 方法用於將每個轉義序列替換為其實際字元。在此示例中,\n 替換為 \n,\t 替換為 \t,\r 替換為 \r。生成的字串將列印每個轉義序列替換為其實際字元。

# replace escape sequences with their actual characters
string = 'This\nstring\thas\r\nescapes'
string = string.replace('\n', '\n')
string = string.replace('\t', '\t')
string = string.replace('\r', '\r')
print(string)

輸出

This
string	has
escapes

使用 replace() 方法替換轉義序列

示例

在此示例中,我們使用 replace() 方法將轉義序列替換為其實際字元。我們首先定義一個包含換行符和製表符轉義序列的示例字串。然後,我們使用 replace() 方法將轉義序列 '\n' 和 '\t' 分別替換為其實際字元 '\n' 和 '\t'。最後,我們列印處理後的字串。

# sample string with escape sequence
text1 = "This is a newline \n and this is a tab \t character."
# replace escape sequences with actual characters
text2 = text1.replace('\n', '\n').replace('\t', '\t')
# print the processed string
print(text1)
print(text2)

輸出

This is a newline 
 and this is a tab  character.
This is a newline \n and this is a tab \t character.

使用 encode() 方法處理轉義序列

示例

在此示例中,我們使用 encode() 方法處理字串中的轉義序列。我們首先定義一個包含換行符和製表符轉義序列的示例字串。然後,我們使用 'unicode_escape' 編碼使用 encode() 方法將字串編碼為帶轉義序列的位元組。最後,我們解碼位元組為字串並使用切片從字串中刪除 b'' 和引號。生成的字串包含已處理的轉義序列。最後,我們列印處理後的字串。

# sample string with escape sequence
text = "This is a newline \n and this is a tab \t character."

# encode the string to bytes
text = text.encode('unicode_escape')
# decode the bytes to string and remove b'' and quotes from the string
text = str(text)[2:-1]
# print the processed string
print(text)

輸出

This is a newline \n and this is a tab \t character.

使用 replace() 方法替換轉義序列

示例

此示例中程式碼的第一行只是建立一個字串變數 text,其中包含一些轉義序列,特別是換行符 (\n) 和製表符 (\t) 字元。

第二行使用 replace() 方法將每個轉義序列 (\n 和 \t) 替換為其相應的字元 (\n 和 \t)。這有效地將轉義序列轉換為實際的換行符和製表符。

replace() 方法在此行中呼叫了兩次,一次用於每個轉義序列。replace() 方法的第一個引數是要替換的子字串,第二個引數是要替換它的子字串。

第三行只是將處理後的字串列印到控制檯。

# sample string with escape sequence
text = "This is a newline \n and this is a tab \t character."
# replace escape sequences with their corresponding characters
text = text.replace('\n', '\n').replace('\t', '\t')
# print the processed string

print(text)

輸出

This is a newline 
 and this is a tab character.

更新於: 2023年8月11日

2K+ 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告

© . All rights reserved.