如何在Python中将变量转换为字符串

8

我有类似的问题,但是我不知道这个术语是什么

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

它应该打印出来

cat5
dog3
fish7

我在想是否有实际的方法或函数可以用来检索作为字符串使用的变量名称。


为什么不使用Python字典呢? - arikel
有没有一种方法可以不使用字典来做到这一点? - thelost
1
相关:https://dev59.com/CnRB5IYBdhLWcg3wtJKF请仅返回翻译后的文本。 - David Brown
2
为什么需要避免使用字典? - Rik Poggi
9个回答

15

你基本上在问:“我的代码如何发现一个对象的名称?”

def animal_name(animal):
    # here be dragons
    return some_string

cat = 5
print(animal_name(cat))  # prints "cat"

在这里,来自comp.lang.python的Fredrik Lundh()的一句引用特别适合。

和你在门廊上找到的那只猫的名字一样:猫(对象)本身无法告诉你它的名字,而且它其实也不关心——所以找出它叫什么名字的唯一方法就是询问所有的邻居(命名空间)是否它是他们的猫(对象)…

...不要惊讶地发现它可能有许多名称,或者根本没有名称!

只是为了好玩,我尝试使用sysgc模块来实现animal_name,并发现周围的人也称您所喜爱的“猫”,即字面整数5,有几个名称:

>>> 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']

对于足够独特的对象,有时你确实可以获得唯一的名称:

>>> mantis_shrimp = 696969; animal_name(mantis_shrimp)
['mantis_shrimp']

因此,总结一下:

  • 简短的答案是:你不能。
  • 长的答案是:好吧,实际上,您有时可以 - 至少在CPython实现中。要查看我示例中如何实现animal_name,请单击此处
  • 正确的答案是:使用dict,就像其他人提到的那样。 当您实际需要使用名称<-->对象关联时,这是最佳选择。

1
我认为可以使用 traceback,这是我在某个地方读到的。我可以故意使用变量引发错误,并将此错误放入字符串中,然后使用正则表达式检索变量。 - thelost
一个有趣的想法!如果你用这种方法取得了一些成功,我会很感兴趣听听。 - wim

5

使用字典而非一堆变量。

animals = dict(cat=5, dog=3, fish=7)

for animal, count in animals.iteritems():
    print animal, count

请注意,它们可能不会(很可能不会)按照您放置的顺序出现。您可以使用collections.ordereddict来解决这个问题,或者如果您仅需要它们以一致的顺序排列,可以通过对键进行排序来解决:
for animal in sorted(animals.keys()):
    print animal, animals[animal]

2

好的,使用f-strings进行工作:

cat = 5

print(f"{cat=}")

Result:

cat=5


1
myAnimals = {'cat':5,'dog':3,'fish':7}
animals = ['cat','dog','fish']
for animal in animals:
    if myAnimals.has_key(animal): print animal+myAnimals(animal)

1

我会将变量放入字典而不是列表中。

d={}
d['cat']=5
d['dog']=3
d['fish']=7

for item in d.keys():
  print item+' '+d[item]

0
我建议使用字典变量,这样可以轻松地将字符串名称映射到相应的值。
animalDict['cat'] = 5
animalDict['dog'] = 3

然后,您可以遍历键并打印出您想要的内容。

0
你把变量名和动物名称的字符串混淆了:
在这里:
cat = 7 

cat是变量,7是它的值

输入:

cat = 'cat'

cat仍然是变量,'cat'是动物名称的字符串。您可以在cat中放置任何字符串,甚至cat = 'dog'

现在回到您的问题:您想打印出动物的名称和相应的数字。

为了配对名称和数字,最好选择使用dict,即字典。 {}表示字典(有时也表示set

d = {3: 'cat', 5: 'dog', 7: 'fish'}

d 是你的变量。{3: 'cat', 5: 'dog', 7: 'fish'} 是你的字典。3, 5, 7 是这个字典的,而'cat'、'dog'、'fish'则是相应的值。
现在你需要迭代这个字典。可以通过调用d.items()来完成:

d = {3: 'cat', 5: 'dog', 7: 'fish'}
for key,value in d.items():
    print(value, key)

我在打印时反转了值和键的顺序,以便先打印名称再打印数字。


0

这是一个很老的问题,但为了准确性我们可以使用它

[name for name, obj in globals().items() if eval(name) in animals]

  • 我们得到
['cat', 'dog', 'fish']
  • 数据
cat = 5
dog = 3
fish = 7
animals= [cat, dog, fish]

0

fadop3的答案的另一种形式

cat = 5
cat = '%s' % cat

这将把cat变量转换为字符串。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接