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

convert string to float and then back to string

I’d like to change value in a dictionary which use string as value. Here is what I did and it didn’t work.

extra_offset_left=0.4
style_image={'height':'300px','width': '100%','padding-left':'12%', 'padding-right':'10%'}

style_image['padding-left']=str(float(style_image['padding-left'])+extra_offset_left)

then i got an error of

ValueError: could not convert string to float: '12%'

What I expect is ‘padding-left’ becomes 12%+0.4=52%

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

'padding-left':'52%' 

Thanks for your help

>Solution :

You can convert the digits to an integer and perform the addition:

style_image['padding-left'] = f"{int(style_image['padding-left'][:-1]) + int(100 * extra_offset_left)}%"

This outputs:

{'height': '300px', 'width': '100%', 'padding-left': '52%', 'padding-right': '10%'}
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