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

Format string dùng dictionary trong Python 3

Dùng dictionary interpolate string. Cú pháp: cung cấp key trong ngoặc đơn giữa % và conversion character. Ví dụ, nếu float lưu ở key 'cost' muốn format '$xxxx.xx', đặt '$%(cost).2f' tại vị trí hiển thị.

Ví dụ dùng string formatting trong dict interpolate string và format số:

>>> print('%(language)s has %(number)03d quote types.' % {'language': "Python", "number": 2})
Python has 002 quote types.

Đọc thêm: https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting