简体   繁体   中英

How to string formatting a variable?

Here is my script:

# I have 100 variables
x0 = 3.14
x1 = 2.72
x2 = 1.41
x3 = 2.33
.... (omit this part)
x100 = 7.77

# xi corresponds to the value that the index i of a list needs to subtract, 
# now I want to loop through the list
for i in range(100):
    lst[i] -= 'x{}'.format(i)

This clearly won't work, since the variable is not a string. So how should I string formatting a variable?

You should instead use a list here.

x = [...] (where x has a len of 100)

Then for your loop:

for i in range(100):
    lst[i] -= x[i]

(Renamed list to lst to avoid name collision with the built-in type)

You can access these variables usinglocals :

lst[i] -= locals()['x{}'.format(i)]

In order to get the value of the variable, you can use Python's eval function

eval('x{}'.format(i))

And please, don't ever call your list variable list.

Edit: While this solution works in this case, it is recommended to avoid eval as much as possible because it allows code injections in a way you wouldn't expect.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM