简体   繁体   中英

variable number of leading zeros

In Python we can do

"file_{:03}.ext".format(i)

allowing us to easily pad any number i with leading zeros to fit any given width.

But what if the desired width is only known at runtime? Can we still achieve the same effect?

Sure, string formatting supports nesting.

>>> "file_{:0{}}.ext".format(42, 3)
'file_042.ext'
>>> "file_{:0{}}.ext".format(42, 5)
'file_00042.ext'

Since you didn't specify the python version I'll state this is also easily done with f-strings as well. (py3.6+)

>>> value = 42
>>> width = 3
>>> f"file_{value:0{width}}.ext"
'file_042.ext'
>>> width = 5
>>> f"file_{value:0{width}}.ext"
'file_00042.ext'

Yes!

Given a desired integer width d , first create a format string via string concatenation, then call format.

d = 3
format_string = "file_{:0" +str(d) + "}.ext"
format_string.format(d)

yields

'file_003.ext'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM