欢迎访问我的网站,希望内容对您有用,感兴趣的可以加入免费知识星球。

python字符串前面补0

Python基础 迷途小书童 3年前 (2020-12-17) 1812次浏览 0个评论

软硬件环境

  • windows 10 64bit
  • anaconda with python 3.7

前言

在实际项目中,经常需要在数字或者数字字符串前面补0,以满足字符个数的要求。比如常见的工号,1、2、3 … 99、100 …,有些系统可能就会要求工号是001、002、003。本文就来分享几种实现该需求的方法。

格式化方法

可以使用格式化的方法,简单方便

(base) PS C:\Users\Administrator> ipython
Python 3.7.6 (default, Jan  8 2020, 20:23:39) [MSC v.1916 64 bit (AMD64)]
Type 'copyright', 'credits' or 'license' for more information
IPython 7.12.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: number = 1

In [2]: '%03d' % number
Out[2]: '001'

In [3]: number2 = 1

In [4]: '{:03d}'.format(number2)
Out[4]: '001'

In [5]:

zfill方法

python 中有一个内置方法 zfill,可以用来给字符串前面补0,非常有用。zfill 是针对字符串的,所以碰到数字的话,需要进行转换

(base) PS C:\Users\Administrator> ipython
Python 3.7.6 (default, Jan  8 2020, 20:23:39) [MSC v.1916 64 bit (AMD64)]
Type 'copyright', 'credits' or 'license' for more information
IPython 7.12.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: number = 1

In [2]: str(number).zfill(3)
Out[2]: '001'

In [3]: number1 = '1'

In [4]: number1.zfill(3)
Out[4]: '001'

In [5]: number2 = -1

In [6]: str(number2).zfill(3)
Out[6]: '-01'

In [7]:

rjust

另一种是使用 rjust 方法,它返回一个原字符串右对齐,并使用指定字符填充至某一特定长度的新字符串。如果指定的长度小于字符串的长度则返回原字符串。与 rjust 对应,还有方法 ljust,它的作用是进行字符串左对齐

(base) PS C:\Users\Administrator>
(base) PS C:\Users\Administrator> ipython
Python 3.7.6 (default, Jan  8 2020, 20:23:39) [MSC v.1916 64 bit (AMD64)]
Type 'copyright', 'credits' or 'license' for more information
IPython 7.12.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: number = 1

In [2]: str(number).rjust(3, '0')
Out[2]: '001'

In [3]: str(number).rjust(3, 'x')
Out[3]: 'xx1'

参考资料

喜欢 (1)

您必须 登录 才能发表评论!

Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

请关闭 Adblock 等类似浏览器插件,然后刷新页面访问,感谢您的支持!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.