3

I have searched but only found items showing leading zeros, not this edge case: I need to have the equivalent of Excel's # in a number format, (which results in 0 displaying a result of zero length, or empty string)

if I do

i = 0
'{}{:02}'.format('prefix', i)

I get

prefix00 

(as expected from PEP 3101), however specifying a width of 0 does not produce what I need. which is something like

i = 0
'{}{:0}'.format('prefix', i)

to produce

prefix

rather than

prefix0

as I currently get. Is this inconsistent in the string format function? Is there a way to create this in the format specifier (rather than a explicit test for zero?)

CestLaGalere
  • 2,909
  • 1
  • 20
  • 20

2 Answers2

1

Ternary conditional format pattern for the win:

for k in range(5):
    print( ('{}' if k == 0 else '{}{:02}').format('prefix', k))

Output:

prefix
prefix01
prefix02
prefix03
prefix04

The pattern changes based on k's value - if you have too many params inside format it works,too few would throw an IndexError.


You could also go for

for k in range(5):
    print( 'prefix' if k == 0 else f'prefix{k:02}' )

using python 3.6 string literal interpolation.

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
  • This works, but "Is there a way to create this in the format specifier (rather than a explicit test for zero?)" – Blorgbeard May 23 '19 at 15:45
  • @Blorg not that I can think of - this is about the simples way to make it happen - you could also construct something with a formatfunction that inspects k or fiddle around with `strip('0')` afterwards if only 1 digit is at the end and it is 0 etc. but I think its more clunky – Patrick Artner May 23 '19 at 15:48
1

You could use this:

n=0
"{}{}".format("prefix",n or "")

or

f"prefix{n or ''}"
Alain T.
  • 40,517
  • 4
  • 31
  • 51