如何在python中将变量转换为字符串 [英] How to convert variable into string in python
问题描述
我有一个类似的问题,但我不知道这个术语是什么
cat = 5狗 = 3鱼 = 7动物= [猫,狗,鱼]对于动物中的动物:# 动物名,我的意思是正在使用的变量名打印(动物名称 + 字符串(动物))
它应该打印出来
cat5狗3鱼7
所以我想知道是否有一个实际的方法或函数可以用来检索用作字符串的变量名称.
您基本上是在问我的代码如何发现对象的名称?"
def 动物名称(动物):#这里是龙返回 some_string猫 = 5print(animal_name(cat)) # 打印猫";
A 引用<来自 Fredrik Lundh(在 comp.lang.python 上)的/a> 在这里特别很合适.
<块引用>与您在门廊上找到的那只猫的名字相同:猫(对象)本身不能告诉你它的名字,它也不会真的很在乎——所以要知道它叫什么的唯一方法就是问你所有的邻居(命名空间),如果是他们的猫(对象)......
....如果您发现它有很多名字,请不要感到惊讶,或者根本没有名字!
只是为了好玩,我尝试使用 sys
和 gc
模块来实现 animal_name
,发现邻居也在调用你的对象亲切地称为猫",即文字整数 5,有几个名称:
对于足够独特的对象,有时您可以获得一个独特的名称:
<预><代码>>>>mantis_shrimp = 696969;动物名称(螳螂虾)['螳螂虾']所以,总结一下:
- 简短的回答是:你不能.
- 长的答案是:嗯,实际上,您有时可以 - 至少在 CPython 实现中.要了解如何在我的示例中实现
animal_name
,请查看此处. - 正确答案是:使用
dict
,正如其他人提到的那样.当您确实需要使用名称 <--> 时,这是最佳选择.对象关联.
I have a problem similar to this, however I do not know what the term is
cat = 5
dog = 3
fish = 7
animals= [cat, dog, fish]
for animal in animals:
# by animal name, I mean the variable name that's being used
print(animal_name + str(animal))
It should print out
cat5
dog3
fish7
So I am wondering if there is an actual method or function I could use to retrieve the variable name being used as a string.
You are basically asking "How can my code discover the name of an object?"
def animal_name(animal):
# here be dragons
return some_string
cat = 5
print(animal_name(cat)) # prints "cat"
A quote from Fredrik Lundh (on comp.lang.python) is particularly appropriate here.
The same way as you get the name of that cat you found on your porch: the cat (object) itself cannot tell you its name, and it doesn’t really care — so the only way to find out what it’s called is to ask all your neighbours (namespaces) if it’s their cat (object)…
….and don’t be surprised if you’ll find that it’s known by many names, or no name at all!
Just for fun I tried to implement animal_name
using the sys
and gc
modules, and found that the neighbourhood was also calling the object you affectionately know as "cat", i.e. the literal integer 5, by several names:
>>> cat, dog, fish = 5, 3, 7
>>> animal_name(cat)
['n_sequence_fields', 'ST_GID', 'cat', 'SIGTRAP', 'n_fields', 'EIO']
>>> animal_name(dog)
['SIGQUIT', 'ST_NLINK', 'n_unnamed_fields', 'dog', '_abc_negative_cache_version', 'ESRCH']
>>> animal_name(fish)
['E2BIG', '__plen', 'fish', 'ST_ATIME', '__egginsert', '_abc_negative_cache_version', 'SIGBUS', 'S_IRWXO']
For unique enough objects, sometimes you can get a unique name:
>>> mantis_shrimp = 696969; animal_name(mantis_shrimp)
['mantis_shrimp']
So, in summary:
- The short answer is: You can't.
- The long answer is: Well, actually, you sometimes can - at least in the CPython implementation. To see how
animal_name
is implemented in my example, look here. - The correct answer is: Use a
dict
, as others have mentioned. This is the best choice when you actually need to use the name <--> object association.
这篇关于如何在python中将变量转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!