Home > database >  Pad string to the left of a character
Pad string to the left of a character

Time:10-21

I have a float that is stored as a string:

float1 = 638045.11 float2 = 638045.1

I want to print this:

float1 = 0000638045.11 float2 = 0000638045.1

I've tried zfill but that pads the entire string. How can I pad only to the left of the decimal?

CodePudding user response:

You can use str.split to spilt the string to the left and right parts then use zfill on the left part.

float1 = 638045.11 
float2 = 638045.1

sf11, sf12 = str(float1).split('.') # -> ['638045', '11']
sf21, sf22 = str(float2).split('.') # -> ['638045', '1']

print(f"{sf11.zfill(10)}.{sf12}")
print(f"{sf21.zfill(10)}.{sf22}")

Output:

0000638045.11
0000638045.1
  • Related