本文共 1177 字,大约阅读时间需要 3 分钟。
python zfill
Python String zfill(width) function returns a new string of specified width. The string is filled with 0 on the left side to create the specified width.
Python字符串zfill(width)函数返回指定宽度的新字符串。 该字符串在左侧用0填充以创建指定的宽度。
If the string starts with sign characters (+,-) then the padding is done after the sign. If the specified width is less than the original string, then the original string is returned.
如果字符串以符号字符(+,-)开头,则在符号之后进行填充。 如果指定的宽度小于原始字符串,则返回原始字符串。
Let’s look at some examples of zfill() function.
让我们看一下zfill()函数的一些示例。
s = '100'print(s.zfill(6))s = '+100'print(s.zfill(6))s = '-100'print(s.zfill(6))
Output:
输出:
000100+00100-00100
Let’s see what happens when the specified width is smaller than the string length.
让我们看看当指定的宽度小于字符串长度时会发生什么。
s = '+100'print(s.zfill(3))
Output: +100
输出: +100
This function is useful when the string is numeric in nature. However, it works with any non-numeric string too.
当字符串本质上是数字时,此功能很有用。 但是,它也适用于任何非数字字符串。
s = 'abc'print(s.zfill(6))s = '+abc'print(s.zfill(6))
Output:
输出:
000abc+00abc
Official Documentation:
官方文档:
翻译自:
python zfill
转载地址:http://elmzd.baihongyu.com/