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

用零填充数字字符串

  1. num = 123
  2. print('{:<08d}'.format(num))
  3. print('{:>08d}'.format(num))
  4. string = '123'
  5. print(string.ljust(8, '0'))
  6. print(string.rjust(8, '0'))
  7. print(string[::-1].zfill(8)[::-1])

Output:

  1. 12300000
  2. 00000123
  3. 12300000
  4. 00000123
  5. 12300000