Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Chuyển đổi bất kỳ kiểu dữ liệu nào thành string trong Python (str())

Hàm tích hợp str() chuyển bất kỳ đối tượng nào thành biểu diễn chuỗi.

Ví dụ các kiểu built-in

>>> str(10)           # int
'10'
>>> str(11.11)        # float
'11.11'
>>> str(3+4j)         # complex
'(3+4j)'
>>> str([1, 2, 3])    # list
'[1, 2, 3]'
>>> str((1, 2, 3))    # tuple
'(1, 2, 3)'
>>> str({1: 11, 2: 22})  # dict
'{1: 11, 2: 22}'

Tùy chỉnh cho class tự định nghĩa

Triển khai phương thức __str__():

class Rectangle:
    def __init__(self, l, b):
        self.l = l
        self.b = b
    def __str__(self):
        return f'length={self.l} breadth={self.b}'

r = Rectangle(10, 5)
print(str(r))  # length=10 breadth=5

Lưu ý: repr() dành cho biểu diễn unambiguous (dành cho developer/debug), str() cho end-user.