Convert string to char in python

Convert string to char in python

No. Use a dictionary.

>>> names = {p1: 100, p2: 200}
>>> t = names[p1]
>>> t

This will throw a KeyError if the name does not exist:

>>> t = names[p3]
Traceback (most recent call last):
  File <stdin>, line 1, in <module>
KeyError: p3

… but you can use dict.get and provide a default value:

>>> t = names.get(p3, default)
>>> t

where the default-default-value is None.

(By the way, this has nothing to do with converting strings to a char(acter?), your terminology is quite confusing.)

Youre probably looking for eval():

p1 = 100
print(eval(p1))   # prints 100

If you want to evaluate expressions you can also use exec()

p1 = 100
t = p1 += 99
print(p1)           # prints 199

But as other already pointed out, you should avoid it if possible.
timgeb provided a nice alternative with dictionaries for example.

If you want to turn a string into a global variable you could also do:

globals()[y] = 5

Note: when you run your code in a global scope (outside a function), you can also use locals()[y] = 5but this will not work in a non-global scope!

Convert string to char in python

if you want to change it into character then do not use char
in python the char is declared as chr
so you can go like:

chr(input(Enter here))

Leave a Reply

Your email address will not be published. Required fields are marked *