Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
70 views
in Technique[技术] by (71.8m points)

python - Get name of every variable in a list and convert to string

Is there a simple way of getting the name(not contents) of every list item and converting it to string?


text0= " zero zero zero zero..."
text1= " one one one.... "
text2= " two two two...."
text3= " three three...."


text_grouped=[text0, text1, text2, text3]

for i in text_grouped:
    print(i)

the above prints the contents of variables but not the actual names.

I would like the result to be: text0, text1, text2, text3

question from:https://stackoverflow.com/questions/65859635/get-name-of-every-variable-in-a-list-and-convert-to-string

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use the varname library (its not part of the standard python library, so you have to install it). Sample code:

from varname import nameof

some_var1 = "somevar1"
some_var2 = "somevar2"
lst = [somevar1, somevar2]
print(nameof(lst[0]), nameof(lst[1]))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...