Python ascii() 函式



Python ascii() 函式 是一個內建函式,用於返回指定物件的易讀版本。這裡,物件可以是字串、元組、列表等。如果此函式遇到非 ASCII 字元,它將用跳脫字元替換它,例如 \x、\u 和 \U。

當我們需要確保最終結果符合 ASCII 標準時,此函式很有用,ASCII 標準是字元編碼標準,代表美國資訊交換標準程式碼。

語法

以下是 Python ascii() 函式的語法:

ascii(object)

引數

Python ascii() 函式接受一個引數:

  • object − 它表示一個物件,例如列表、字串或元組。

返回值

Python ascii() 函式返回一個包含物件可打印表示形式的字串。

示例

讓我們透過一些示例瞭解 ascii() 函式的工作原理:

示例 1

以下示例顯示瞭如何使用 Python ascii() 函式。這裡我們定義了一個字串並應用 ascii() 函式將其轉換為包含 ASCII 字元的字串。由於它已經包含 ASCII 字元,因此結果將與原始字串相同。

orgnl_str = "Learn Python Methods"
new_ascii_str = ascii(orgnl_str)
print("The new ascii representation of given string:", new_ascii_str)  

當我們執行上述程式時,它會產生以下結果:

The new ascii representation of given string: 'Learn Python Methods'

示例 2

在以下示例中,我們定義了一個包含一些非 ASCII 字元的字串,並應用 ascii() 函式將其轉換為包含 ASCII 字元的字串。

orgnl_str = "Learn Pythön Methods"
new_ascii_str = ascii(orgnl_str)
print("The new ascii representation of given string:", new_ascii_str)  

當我們執行上述程式時,它會產生以下結果:

The new ascii representation of given string: 'Learn Pyth\xf6n Methods'

示例 3

以下程式碼顯示瞭如何使用 ascii() 函式將包含非 ASCII 字元的列表轉換為包含 ASCII 字元的列表。

orgnl_lst = [71, 87, "é", "→",5]
new_ascii_lst = ascii(orgnl_lst)
print("The new ascii representation of given list:", new_ascii_lst) 

上述程式碼的輸出如下:

The new ascii representation of given list: [71, 87, '\xe9', '\u2192', 5]

示例 4

在下面的程式碼中,建立了一個名為 'orgnl_set' 的集合。然後使用 ascii() 函式替換集合中存在的所有元素。在這裡,我們檢索包含 ASCII 字元的集合。

orgnl_set = {"©", "¥", "é", "→"}
new_ascii_set = ascii(orgnl_set)
print("The new ascii representation of given set:", new_ascii_set)  

以下是上述程式碼的輸出:

The new ascii representation of given set: {'\xa5', '\xa9', '\xe9', '\u2192'}
python_built_in_functions.htm
廣告