当前位置:  首页>> 技术小册>> Python合辑4-130个字符串操作示例

Python填充字符串到固定长度

  1. number = 4
  2. print(f'{number:05d}') # (since Python 3.6), or
  3. print('{:05d}'.format(number)) # or
  4. print('{0:05d}'.format(number))
  5. print('{n:05d}'.format(n=number)) # or (explicit `n` keyword arg. selection)
  6. print(format(number, '05d'))

Output:

  1. 00004
  2. 00004
  3. 00004
  4. 00004
  5. 00004
  6. 00004

该分类下的相关小册推荐: