Skip to content
Advertisement

ValueError: could not convert string to float when adding percentages

I’d like to change value in a dictionary which use string as value. Here is what I did:

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)

I got this error:

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

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

'padding-left':'52%' 

How can I accomplish this?

Advertisement

Answer

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%'}
Advertisement