Home > Software engineering >  I want to assign a string variable inside python raw_input
I want to assign a string variable inside python raw_input

Time:05-01

---reality---

a = "[email protected]"

b = raw_input()
> a            # enter

result : a

---desired answer---

a = "[email protected]"

b = raw_input()
> a            # enter

result : "[email protected]"

When I use it as input, it works normally, but when I use raw_input, why do I get such a result? And what's the solution?

Thank you.

CodePudding user response:

For a toy problem, just use input(). This is the equivalent of eval(raw_input()). Don't do this if there is even the possibility that you do not trust input. Whoever has control of the input can execute arbitrary code in your program. So it's a major security vulnerability.

For a more secure approach, put all the values you want to be accessible in a dictionary, and then key that dictionary by your input. The reason to do it this way is that user can only select from the predefined keys you have given them.

eg.

values = {'a': 1, 'b': 2}
key = raw_input()
result = values[key]
print(result)

A halfway house might be to use globals() or locals(). globals() returns your module's global dictionary and locals() collects all the local variables into a dictionary for you. This will allow the user to select any name from either of those sets of names. So they might be able to select values you want to keep secret.

eg.

password = 'foo'
a = 1
b = 2
key = raw_input() # password would be a valid input here
result = vars()[key]
print(result) # so here we would leak the value of password

As a side note, you are using Python 2. Python 2 is long past its end of life and no longer receives security updates. All new projects should ideally use one of the more recent versions of Python 3 (eg. 3.10). Python 3 only has input(), but its behaviour is that of raw_input() in Python 2.

CodePudding user response:

If you give input, it is considered as string.

You can use dictionary to save your e-mail and then use input string as key to get value (Python3 code):

your_dict = {'a': '[email protected]'}
b = input()
print(your_dict[b])
#[email protected]

CodePudding user response:

What you receive through the input() function will be a string.so you just asking to print that string. you can read more about globals() dynamically assign variables from here. How can you dynamically create variables?

you can use globals() function like this. (Using input() for Python 3.)

a = "[email protected]"

print(globals()[input()])

a

[email protected]

  • Related