Python中字符串中zfill在某种场合的作用

有时候需要求某个10进制的8位二进制,这个时候使用bin(int),来转换:

>>> bin(15)
'0b1111'

这个时候前面自动加上0b,如果要整成八位二进制,又必须做出处理,这个时候使用zfill是个不错的主意:

>>> bin(15)[2:].zfill(8)
'00001111'
>>>

从上面来看,使用zfill自动从左往右填充指定宽度的0

>>> help(str.zfill)
Help on method_descriptor:

zfill(...)
    S.zfill(width) -> string

    Pad a numeric string S with zeros on the left, to fill a field
    of the specified width.  The string S is never truncated.

>>>

猜你喜欢

转载自blog.csdn.net/Jerry_1126/article/details/80862235