如何对一个变量进行字符串格式化?

问题描述 投票:-1回答:1

这是我的脚本。

# 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)

这显然是行不通的,因为变量不是字符串。那么我应该如何对一个变量进行字符串格式化呢?

python python-3.x string-formatting
1个回答
2
投票

你可以通过以下方法访问这些变量 locals:

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

2
投票

为了获得变量的值,你可以使用Python的 评价函数

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

还有,请千万不要把你的列表叫做变量列表。

编辑。 虽然这个解决方案在这种情况下是可行的,但建议尽量避免使用eval,因为它允许以一种你想不到的方式注入代码。


1
投票

你应该使用 list 在这里。

x = [...] (其中 x 拥有 len (100人的)

然后为你的循环。

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

(重命名为 listlst 以避免与内置类型发生名称碰撞)

© www.soinside.com 2019 - 2024. All rights reserved.