-4

Is there a possibility (e.g. a built-in function) to convert a string to a char in python? For example, if I assign a value to the variable

p1=100

and then have the string

"p1",

is it possible to assign the value of p1 to a new variable t like

t=char("p1")

so that I get

print(t)->100 ? 

Obviously, above mentioned solution does not work as it throws following error message:

NameError: name 'char' is not defined

Edit: The question is not about best practices: I know that I should do this with a dictionary, but what I am trying to do is to understand data types in Python and how to convert them. Convert a string to an integer is fairly easy, for example, so I was wondering if the same applies to string to char conversions. The eval() command does solve the example's question, but it does not answer above mentioned problem. So I would edit the goal to

 char("p11")=20

which should give me

 print(p11) -> 20
Paul Rousseau
  • 571
  • 2
  • 7
  • 21
  • 1
    Not sure what you mean. Are you possibly looking for `chr()`? – tonypdmtr May 08 '17 at 13:11
  • I tried, but it gives me another error message: TypeError: an integer is required (got type str) – Paul Rousseau May 08 '17 at 13:11
  • `t = eval('p1')`. But please think of alternative, like the suggested answer below. – Maroun May 08 '17 at 13:12
  • You want "string to char conversion", but there is no `char` datatype in Python. – Matthias May 08 '17 at 14:02
  • 1
    I suggest that you start from reading a Python tutorial. It's an excellent way to familiarize yourself with the language, not typing random bits of code and asking on Stackoverflow why they doesn't work. – Eugene Morozov May 08 '17 at 14:25
  • I believe this is a duplicate of https://stackoverflow.com/questions/11553721/using-a-string-variable-as-a-variable-name, https://stackoverflow.com/questions/1373164/how-do-i-create-a-variable-number-of-variables. – AMC Aug 20 '20 at 19:35

3 Answers3

3

No. Use a dictionary.

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

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
'default'

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.)

timgeb
  • 76,762
  • 20
  • 123
  • 145
  • Yes. It's a bad practice to call directly, too risky. A question was already made into Stack: http://stackoverflow.com/questions/11553721/using-a-string-variable-as-a-variable-name – capcj May 08 '17 at 13:12
  • That's the best solution imo. There's also the get() method `names.get('p1')` – Dawid May 08 '17 at 13:14
2

You're probably looking for eval(): https://docs.python.org/3.5/library/functions.html#eval

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

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

p1 = 100
t = 'p1 += 99'
exec(t)
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
print(y)

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

Mike Scotty
  • 10,530
  • 5
  • 38
  • 50
  • This is the answer I was looking for. Could you please elaborate on why it is so bad? – Paul Rousseau May 08 '17 at 13:19
  • 1
    ``eval()`` could also run malicious code. If you're working with user input, this could be a security risk. – Mike Scotty May 08 '17 at 13:24
  • So if I gather correctly, it does not change the string to a char, but executes the string. That means that if I put eval('p1')=20, it throws following error message: SyntaxError: can't assign to function call – Paul Rousseau May 08 '17 at 13:44
  • 1
    You keep asking for "changing a string to a char", but that does not make sense. If ``eval()`` does not meet your needs you can also try ``exec()`` where you can also work with assignments - I have updated my answer to demonstrate ``exec()`` – Mike Scotty May 08 '17 at 14:05
  • 2
    I'm still super confused what OP means by "char". – timgeb May 08 '17 at 14:09
  • What I mean is that I want to convert a string into a variable name. – Paul Rousseau May 08 '17 at 14:33
  • The exec() command, as well as the eval() command, do not convert a string to a variable name, but run the string as python code, as I understand it now. – Paul Rousseau May 08 '17 at 14:34
  • ``exec`` can create a new variable from a string with an assignment. The following will work, even if you did not define ``x`` prior to executing the code: ``exec('x=100') -> print(x) -> prints 100``. *However* ``exec("x") = 1`` will not work, for the same reasons ``eval("x") = 1`` does not work. – Mike Scotty May 08 '17 at 14:38
  • So the answer is that it is impossible to directly convert a string to a variable name? – Paul Rousseau May 08 '17 at 14:41
  • There is one ... when working with global variables. Give me a sec, I will update the answer once again ;) – Mike Scotty May 08 '17 at 14:42
  • Thank you so much for your help mpf82. (I know that expressions of gratitude are frowned upon on this website, but since I already got 4 down-votes, I guess I have nothing to lose anymore ...;) – Paul Rousseau May 08 '17 at 14:54
0

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'))
VIASK
  • 1