Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pad string to the left of a character

I have a float that is stored as a string:

float1 = 638045.11
float2 = 638045.1

I want to print this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading