Python将整数格式化为固定长度字符串

2024-06-17 15:37:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我想生成一个基于int和零的字符串。长度应该始终是5,不能大于或小于这个值。

For example:

Consider a Integer: 1
Formatted String : 00001

Consider a Integer: 12
Formatted String : 00012

Consider a Integer: 110
Formatted String : 00110

Consider a Integer: 1111
Formatted String : 01111

Consider a Integer: 11111
Formatted String : 11111

Tags: 字符串forstringexampleintegerintformattedconsider
1条回答
网友
1楼 · 发布于 2024-06-17 15:37:53

使用^{} function^{}方法格式化零填充的整数:

print format(integervalue, '05d')
print 'Formatted String : {0:05d}'.format(integervalue)

请参阅格式中的Format Specification Mini-Language;前导的0表示0填充,5是最小字段宽度;任何小于该宽度的数字都填充到全宽度。

演示:

>>> format(110, '05d')
'00110'
>>> 'Formatted String : {0:05d}'.format(12)
'Formatted String : 00012'

相关问题 更多 >