-1

I have a string with len of 2 or 3

s1 = 22
s2 = 27
s3 = 102

I want to return a string with 3 chars. If orig string was len of 2 - add 0 at the begginig. So output will be:

"022" , "027", "102".

Is there an elegant/one liner to do it in Python?

Cranjis
  • 1,590
  • 8
  • 31
  • 64

2 Answers2

2

there's a str method just for this!

s.zfill(3)
acushner
  • 9,595
  • 1
  • 34
  • 34
0

Use fstring with number of digits followed by digit value.

s = 22
f'{s:03}'
>> '022'
Hamza usman ghani
  • 2,264
  • 5
  • 19