Home > OS >  Can not print an assigned variable, the console prints the string
Can not print an assigned variable, the console prints the string

Time:06-26

I am trying to automatize a process. I need to extract a string and previously assigned it a variable. For example:

H=8
Hello= "Hello"
Hi=(Hello[0])
print(H)
print(Hi)

Console prints:

8
H

and I need the console to print:

8
8

CodePudding user response:

Use a dictionary instead.

Any method that solves this how you want it to be solved will be unsafe and bad practice.

data = {'H': 8, 'B': 3}
Hello = "Hello"
Hi = data[Hello[0]]
print(data['H'])
print(Hi)

Output:

8
8

See: Why is using 'eval' a bad practice?

CodePudding user response:

You can use globals() like below: (Also recommend you read this : What's the difference between globals(), locals(), and vars()?)

From the above link:

  • globals() always returns the dictionary of the module namespace
H=8
Hello= "Hello"
Hi=globals()[Hello[0]]
print(H)
print(Hi)

Output:

8
8
  • Related