-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?

okuoub
  • 716
  • 6
  • 19
  • 52

2 Answers2

2

there's a str method just for this!

s.zfill(3)
acushner
  • 8,972
  • 1
  • 32
  • 32
0

Use fstring with number of digits followed by digit value.

s = 22
f'{s:03}'
>> '022'
Hamza usman ghani
  • 2,149
  • 4
  • 18