Home > OS >  Print list with variable name in it (as it appears in source code file)?
Print list with variable name in it (as it appears in source code file)?

Time:01-18

I have a Python list:

L1 = [['Hello', '.', 'My', 'name', 'is', 'Joe'],['Hola', '.', 'Mi', 'nombre', 'es', 'Joe']]

How do I print the list to get this output:

L1 = [['Hello', '.', 'My', 'name', 'is', 'Joe'],['Hola', '.', 'Mi', 'nombre', 'es', 'Joe']]

The same as what is in my .py file?

A similar question appears for Go: Golang: print struct as it would appear in source code

But I do not understand it and if Python has anything similar.

For those wanting to know why, I need to print these lists to an HTML file. Due to limitations of programming interoperability and not wanting to over-engineer, this is easiest for me to use as code.

CodePudding user response:

Use an f-string as follows:

L1 = [['Hello', '.', 'My', 'name', 'is', 'Joe'],['Hola', '.', 'Mi', 'nombre', 'es', 'Joe']]

print(f'{L1 = }'.replace(', [', ',['))

Output:

L1 = [['Hello', '.', 'My', 'name', 'is', 'Joe'],['Hola', '.', 'Mi', 'nombre', 'es', 'Joe']]

Without the call to replace() the output will be:

L1 = [['Hello', '.', 'My', 'name', 'is', 'Joe'], ['Hola', '.', 'Mi', 'nombre', 'es', 'Joe']]

CodePudding user response:

This is not a method I will not encourage you to use, but if you are really sure you want to do this you can do it like this.

I assume that you have a variable which you want to print.

L1 = [['Hello', '.', 'My', 'name', 'is', 'Joe'],['Hola', '.', 'Mi', 'nombre', 'es', 'Joe']]

# make a copy of the globals
g = globals().copy()

for key, value in g.items():
    if value is L1:
        break

print(f"{key} = {value}")

Again, I do not recommend you to use it.

  • Related