Python repr() 函式



Python 的 repr() 函式用於獲取物件的字串表示形式。

此函式對於除錯和記錄目的非常有用,因為它與 str() 函式相比,提供了物件更詳細、更清晰的表示形式。雖然 str() 主要用於建立人類可讀的字串,但 repr() 提供的字串在傳遞給 eval() 函式時,可以重新建立原始物件。

語法

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

repr(x)

引數

此函式將一個物件 'x' 作為引數,您希望獲取該物件的字串表示形式。

返回值

此函式返回一個字串,當作為 Python 程式碼執行時,將重新建立原始物件。

示例 1

在下面的示例中,我們使用 repr() 函式獲取字串物件 "Hello, World!" 的字串表示形式:

text = "Hello, World!"
representation = repr(text)
print('The string representation obtained is:',representation)

輸出

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

The string representation obtained is: 'Hello, World!'

示例 2

在這裡,我們使用 repr() 函式獲取整數物件 "42" 的字串表示形式:

number = 42
representation = repr(number)
print('The string representation obtained is:',representation)

輸出

以上程式碼的輸出如下:

The string representation obtained is: 42

示例 3

在這裡,我們獲取列表 "[1, 2, 3]" 的字串表示形式。輸出是一個字串,在 Python 程式碼中使用時,將重新建立原始列表:

my_list = [1, 2, 3]
representation = repr(my_list)
print('The string representation obtained is:',representation)

輸出

獲得的結果如下所示:

The string representation obtained is: [1, 2, 3]

示例 4

在這種情況下,repr() 函式與複數 "(2+3j)" 一起使用:

complex_num = complex(2, 3)
representation = repr(complex_num)
print('The string representation obtained is:',representation)

輸出

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

The string representation obtained is: (2+3j)

示例 5

在此示例中,我們定義了一個名為 "Point" 的自定義類,它具有 "x" 和 "y" 屬性來表示座標。此外,我們在類中實現了 "repr" 方法以自定義字串表示形式。之後,我們建立了一個名為 "point_instance" 的類的例項,其座標為 "(1, 2)"。透過使用 repr() 函式,我們獲取格式化的字串 "Point(1, 2)",表示點的座標:

class Point:
   def __init__(self, x, y):
      self.x = x
      self.y = y
   def __repr__(self):
      return f'Point({self.x}, {self.y})'
point_instance = Point(1, 2)
representation = repr(point_instance)
print('The string representation obtained is:',representation)

輸出

產生的結果如下:

The string representation obtained is: Point(1, 2)
python_type_casting.htm
廣告