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?
CodePudding user response:
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%'}
CodePudding user response:
I know this answer doesn't exactly answer OP's question, but since we're talking about a value that will be passed down to CSS, CSS has the calc helper function that allows to do operations over css values. That means that you can, instead of computing this by yourself, leave it to css! Here's an example:
extra_offset_left=0.4
style_image={'height':'300px','width': '100%','padding-left':'12%', 'padding-right':'10%'}
style_image['padding-left']=f"calc({style_image['padding-left']} {int(100 * extra_offset_left)}%)"
and get the following:
{'height':'300px','width': '100%','padding-left':'calc(12% 40%)', 'padding-right':'10%'}
And the computed css value of that expression will be padding-left: 52%