How can I turn a regular string into a keyword? [duplicate] - python

This question already has answers here:
Converting String into Object Python
(2 answers)
Closed 9 years ago.
Recently, I have been programming in the language of Python. I've came across the problem of trying to convert a string into a keyword.
Suppose I use a raw_input() phrase and turn that string into an object, list, or dictionary.
For example, I can turn the string "Foo" into Foo and assign that name to a python structure.
How would I do this?

You don't want to do that, so instead of doing it, use a dictionary:
answer = raw_input("Enter: ") # Let's assume I enter "Foo"
mydict = {answer: raw_input("Enter a value for {} ".format(answer)} Let's say I enter "5"
print mydict.get('Foo')
# 5

You can modify the globals dictionary if you wish.
globals()[raw_input()] = None # whatever "structure" you desire.
print foo
The above code would only work if the user actually inputted the string 'foo'. Otherwise it would say NameError: name 'foo' is not defined.
But yeah like Haidro said, whatever you're trying to do this for is probably a silly idea.
As #icktoofay noted in the comments, this will only work with the return value of the built-in function globals(). Modifying the return value of the built-in function locals() will not actually modify the local namespace.

Related

Can we use a variable to create a new variable in Python? [duplicate]

This question already has answers here:
Which is the preferred way to concatenate a string in Python? [duplicate]
(12 answers)
Closed 5 months ago.
I am wondering if we can use a variable name in order to create a new variable, for example:
Let's assume I have this variable:
Var = 'Jim'
Lets say I want to concatenate the variable with a string, in this case the string is the word Mr:
NewVar = "String"Var
So that if I print the new variable, the output would look something like:
MrJim
This can be achieved in bash like this:
NewVar=Mr${Var}
But I have not found a way to do this in Python. Please let me know if you know how to do it.
Have a look at python string interpolation.
var = "Jim"
new_var = f"Mr {var}"

From string to fstring [duplicate]

This question already has answers here:
Transform string to f-string
(5 answers)
Closed 2 years ago.
I'm trying to pull a string from JSON, then convert it to an f string to be used dynamically.
Example
Assigned from JSON I get
whose_fault= "{name} started this whole mess"
How to build a lambda to convert it to an f-string and insert the given variable? I just can't quite get my head around it.
I know similar questions have been asked, but no answer seems to quite work for this.
Better question. What's the most pythonic way to insert a variable into a string (which cannot be initially created as an f-string)?
My goal would be a lambda function if possible.
The point being to insert the same variable into whatever string is given where indicated said string.
There is no such thing as f-string type object in python. Its just a feature to allow you execute a code and format a string.
So if you have a variable x= 2020, then you can create another string that contains the variable x in it. Like
y = f"It is now {x+1}". Now y is a string, not a new object type,not a function

Assigning operator to a variable in Python [duplicate]

This question already has answers here:
Python - is there a way to store an operation(+ - * /) in a list or as a variable? [duplicate]
(2 answers)
assign operator to variable in python?
(5 answers)
Closed 9 months ago.
I'm a beginner in Python and I can't figure out the assignment of an operator to a variable.
I've read assign operator to variable in python? but I still can't figure out my problem.
a = str(+)
This line of code gives an Invalid Syntax Error.
Whereas, a =input() works completely fine when we give an operator as input. This operator is stored as string type because whatever you enter as input, input function converts it into a string.
Why str() is not able to store an operator as a string whereas input() can do the same task without any error?
Based on the other post, you'd have to do
import operator
a = operator.add
The answer there just does a lookup in a dictionary
You're not giving an operator to input(), you're always inputting and outputting a string, which could be any collection of characters & symbols
+ is not an identifier or value of any kind; it is part of Python's syntax. You probably want a = str("+") (or simply a = "+").
input doesn't take a value; whatever environment you are running in already takes care of converting your keystrokes to strings for input to read and return.
If you want a to be a callable function, then you can use operator.add as mentioned in #cricket_007's answer (though not passed through str, but used directly per my comment to that answer).
To add to the above answers you can validate the input as an integer:
while True:
try:
userInput = int(input('Enter a number:> '))
except ValueError:
print("Not an integer! Try again.")
continue
else:
return userInput
break

Python Passing list by its name to a function [duplicate]

This question already has answers here:
How can I select a variable by (string) name?
(5 answers)
Closed 8 months ago.
names=['abcd','efgh']
nameoflist='names'
def(nameoflist=[]):
return nameoflist
I want to be able to return the entire list from the function
Assuming names is global as specified in the question, you can do this
names=['abcd','efgh']
nameoflist='names'
def return_names(nameoflist):
return globals()[nameoflist]
However, this is pretty ugly, and I'd probably try another way to do it. What do you need the name for? Is there any other way to get the information you're asking for?
This one way to do what you are asking. But it is not good programming.
names=['abcd','efgh']
def list_by_name(list_name):
return eval(list_name)
print(list_by_name('names'))
Also, argument list_name should be a string. It should not default to a list, which would make the function to fail if called without argument. It should not have a default value.

Cant print an variable associated to a string? [duplicate]

This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 6 years ago.
i was playing around with python and was wondering why i cant print a variable thats associated with a string of text, this is what i wrote.
name = ("martim")
print name
Thanks for your help!
I hope these few lines will help you to understand how to use variables, values and print-statement in Python 2:
>>> name = "martin"
>>> print name
martin
>>> print "name"
name
>>> print "martin"
martin
Also you can take a look at the beginner's guide for Python: https://wiki.python.org/moin/BeginnersGuide
The proper way to perform what you're attempting to do is (note the comments are just to help understanding):
# Set name to "martin"
name = "martin"
# Print the value of name
print(name)
When assigning values to variables, parentheses shouldn't be used unless you're using a function for assignment; e.g., pi = float("3.14"). Print statements require parentheses as it is a function and the value being printed is the parameter.

Categories

Resources