I’d like to change value in a dictionary which use string as value. Here is what I did:
JavaScript
x
6
1
extra_offset_left=0.4
2
style_image={'height':'300px','width': '100%','padding-left':'12%', 'padding-right':'10%'}
3
4
style_image['padding-left']=str(float(style_image['padding-left'])+extra_offset_left)
5
6
I got this error:
JavaScript
1
2
1
ValueError: could not convert string to float: '12%'
2
What I expect is ‘padding-left’ becomes 12%+0.4=52%
JavaScript
1
2
1
'padding-left':'52%'
2
How can I accomplish this?
Advertisement
Answer
You can convert the digits to an integer and perform the addition:
JavaScript
1
2
1
style_image['padding-left'] = f"{int(style_image['padding-left'][:-1]) + int(100 * extra_offset_left)}%"
2
This outputs:
JavaScript
1
2
1
{'height': '300px', 'width': '100%', 'padding-left': '52%', 'padding-right': '10%'}
2