Apollys supports Monica
Apollys supports Monica

Reputation: 3258

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?

Upvotes: 1

Views: 172

Answers (3)

Jab
Jab

Reputation: 27485

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'

Upvotes: 2

Apollys supports Monica
Apollys supports Monica

Reputation: 3258

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'

Upvotes: -1

wim
wim

Reputation: 362587

Sure, string formatting supports nesting.

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

Upvotes: 2

Related Questions