在 Python 中将数字格式化为字符串
Formatting numbers to strings in Python
使用格式化字符串文字将数字格式化为字符串,例如
result = f'{my_int:03d}'
. 格式化字符串文字会将数字格式化为指定宽度的字符串,方法是在左侧填充零或空格。
主程序
my_int = 14 result = f'The number is {my_int}' print(result) # 👉️ The number is 14 # ✅ format integer to string with width 3 (zero-padded) result = f'{my_int:03d}' print(result) # 👉️ '014' # ----------------------------------- # ✅ format integer to string (space-padded) result = f'{my_int:3}' print(repr(result)) # 👉️ ' 14' # ----------------------------------- my_float = 1.234567 # ✅ format float to string with width 8 with 3 decimal places result = f'{my_float:8.3f}' print(repr(result)) # 👉️ ' 1.235' # ✅ format float to a string with width of 4 with 3 decimal places result = f'{my_float:4.3f}' print(repr(result)) # 👉️ '1.235'
第一个示例使用格式化字符串文字将数字格式化为字符串。
格式化字符串文字 (f-strings) 让我们通过在字符串前加上
f
.确保将表达式括在大括号 –{expression}
中。
格式化字符串文字还使我们能够
在表达式块中使用格式特定的迷你语言。
主程序
hours = 7 minutes = 47 seconds = 6 result = f'The time is: {hours:02d}:{minutes:02d}:{seconds:02d} {"pm" if hours > 12 else "am"}' print(result) # 👉️ The time is: 07:47:06 am
该:02d
语法用于将带有前导零的整数填充到固定宽度的 2 位数字。
您可以使用相同的方法将数字格式化为带前导空格的字符串。
主程序
my_int = 14 result = f'{my_int:3}' print(repr(result)) # 👉️ ' 14'
该示例将数字格式化为宽度为 的字符串3
。
如果您只需要用数字执行字符串格式化,请将变量包含在花括号中。
主程序
num1 = 2 num2 = 6 result = f'{num1} + {num2} = {num1 + num2}' print(result) # 👉️ '2 + 6 = 8'
您可以使用相同的方法将浮点数格式化为字符串。
主程序
my_float = 1.234567 # ✅ format float to string with width 8 with 3 decimal places result = f'{my_float:8.3f}' print(repr(result)) # 👉️ ' 1.235' # ✅ format float to a string with width of 4 with 3 decimal places result = f'{my_float:4.3f}' print(repr(result)) # 👉️ '1.235'
冒号后的数字是字符串的总宽度。
句点后的数字是小数点后的位数。
str.zfill()
如果需要将数字格式化为带前导零的字符串,也可以使用该方法。str.zfill方法获取字符串
的宽度并用数字向左填充字符串0
以使其具有指定的宽度。
主程序
my_int = 14 result = str(my_int).zfill(3) print(result) # 👉️ '014' result = str(my_int).zfill(4) print(result) # 👉️ '0014'
将数字转换14
为字符串给我们一个长度为2
.
3
作为宽度传递给该zfill()
方法意味着字符串将左填充一个0
数字。
该方法通过在符号后插入填充来str.zfill()
处理前导符号前缀(例如+
or )。-
主程序
my_int = -14 result = str(my_int).zfill(3) print(result) # 👉️ '-14' result = str(my_int).zfill(4) print(result) # 👉️ '-014'
请注意,符号计入字符串的宽度。
如果指定的宽度小于或等于原始字符串的长度,则返回原始字符串。