如何提取变量名(作为变量列表中的元素)并将其转换为字符串?
nameof()
可以用来将变量的名称打印为字符串,而不是其值本身:
from varname import nameof
var = 'Hello!'
print (nameof(var))
#Output:
var
我需要它的原因是因为我想打印列表的每个元素的值当它正在通过时:
from varname import nameof
green = 3
blue = 6
black = 9
white = 1
purple = 8
list_colors = [green, blue, black, white, purple]
for color in list_colors:
print("The color being looked at is:", nameof(color))
我得到的输出是:
The color being looked at is: color
The color being looked at is: color
The color being looked at is: color
The color being looked at is: color
The color being looked at is: color
但是,我需要以下作为输出(也不是存储在每个变量中的数字值):
The color being looked at is: green
The color being looked at is: blue
The color being looked at is: black
The color being looked at is: white
The color being looked at is: purple
任何人都可以帮助我吗?
nameof()
can be used to print the name of a variable as a string, instead of its value itself:
from varname import nameof
var = 'Hello!'
print (nameof(var))
#Output:
var
The reason why I need this is because I want to print the value of each element of a list as it's being looped through:
from varname import nameof
green = 3
blue = 6
black = 9
white = 1
purple = 8
list_colors = [green, blue, black, white, purple]
for color in list_colors:
print("The color being looked at is:", nameof(color))
The output I get is:
The color being looked at is: color
The color being looked at is: color
The color being looked at is: color
The color being looked at is: color
The color being looked at is: color
But rather, I need the following as the output (and also NOT the numeric values stored in each of the variables):
The color being looked at is: green
The color being looked at is: blue
The color being looked at is: black
The color being looked at is: white
The color being looked at is: purple
Can anyone please help me with this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您想这样做,我从:
我不知道它的工作原理,我会使用一个2D阵列(绝对不是最好的解决方案),但是您可以去。
If you want to do it that way, I found this from:
I have no idea how it works and I would do it with a 2D array (which is definitely not the best solution either), but here you go.
使用
retireve_name
by juan isaza 来自获取变量的名称作为字符串<< /a>输出:
Using
retrieve_name
by juan Isaza from Getting the name of a variable as a stringOutput: