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

标签 python string variables

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

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

所以我想知道是否有实际的方法或函数可以用来检索用作字符串的变量名。

最佳答案

您基本上是在问“我的代码如何发现对象的名称?”

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

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

A quote来自 Fredrik Lundh(在 comp.lang.python 上)特别在这里很合适。

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!

只是为了好玩,我尝试使用 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 实现中。 To see how animal_name is implemented in my example, look here .
  • 正确答案是:使用 dict,正如其他人提到的那样。当您实际需要使用名称 <--> 对象关联时,这是最佳选择。

关于python - 如何在python中将变量转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9121376/

相关文章:

android - 向 parse.com 安装表中的 channel 添加值时出错?

c# - 在 C# 的字符串中间重复一个字符 n 次的最短方法是什么

android - 方法中声明的最终静态 bool 变量

javascript - 如何将变量与Jquery结合起来?

python - python列表中重复项的最后一个索引

python - 使用包含索引的字典填充 NumPy 数组

Java 正则表达式积极向前看但只匹配唯一字符?

ruby-on-rails - 如何在 Ruby 变量名中使用字符串?

python - Django - 如何安装 Python 图像库 (PIL)

python - 如何创建一个字典,其中键是列表中的元素,值是从 1 到 n 的数字?