Convert the string to the variable name in Python
x='buffalo'
exec("%s = %d" % (x,2))
After that you can check it by:
buffalo print
As output you see:2
Convert a string to a variable name in Python
I just made a quick example to do what you want to do. I don't recommend you to do this, but I assume you have a good reason for doing so and will help you.
Variablen = ["a", "b", "c"]
for i in range(len(vars)):
globalis()[vars[i]] = (i+1)*10Print(a) #10
Print(b) #20
Print (c) No. 30
This example can be a bit complicated but it does exactly what you asked for in your question, in short you can use the globals() function to convert a string to a variable. Link to more information here: https://www.pythonpool.com/python-string-to-variable-name/
Convert variable names to string?
TL;DR: That's not possible. See "Conclusion" at the end.
There is one usage scenario where you might need this. I'm not suggesting that there aren't better ways or that they achieve the same functionality.
This would be useful for accidentally "downloading" an arbitrary list of dictionaries, in debugging modes and other similar situations.
What would be needed is the inverse ofEvaluation()
Function:
get_identifier_name_missing_function()
which would take an identifier name ('variable', 'dictionary', etc.) as an argument and return a
String containing the name of the identifier.
Consider the following current situation:
random function (data argument)
If you pass an identifier name ('function', 'variable', 'dictionary', etc.)data argument
for onerandom_function()
(another identifier name), you actually pass an identifier (for example:<argument data object at 0xb1ce10>
) to another identifier (for example:<Random function function at 0xafff78>
):
<random function function at 0xafff78>(<argument data object at 0xb1ce10>)
As I understand it, only the memory address is passed to the function:
<function at 0xafff78>(<object at 0xb1ce10>)
Therefore, it would be necessary to pass a string as an argument torandom_function()
then this function has the name of the argument identifier:
random_function('Datenargument')
Inside the random() function
def random_function(erstes_argument):
, one would use the string already provided'data argument'
for:
serve as an 'identifier name' (for viewing, logging, splitting/concatenating strings, etc.)
(Video) Python Lesson 4 - Getting Input from the User, Converting Variable TypesEssen
Evaluation()
Function to get a reference to the actual identifier and thus a reference to the actual data:print("currently being processed", first_argument)
some_internal_variable = eval(erstes_argument)
print("Here comes the data: " + str(some_internal_var))
Unfortunately, this does not work in all cases. It only works if therandom_function()
can solve that'data argument'
String to a real identifier. I mean yesdata argument
the name of the identifier is available inrandom_function()
of the namespace.
Isn't always like this:
# principal1.py
importar some_module1data_argument = 'my data'
some_module1.random_function('argument_data')
# algun_modulo1.py
def random_function(erstes_argument):
print("currently being processed", first_argument)
some_internal_variable = eval(erstes_argument)
print("Here comes the data: " + str(some_internal_var))
######
The expected results would be:
Work in progress: argument_data
here comes the data: my data
Weildata argument
the identifier name is not available inrandom_function()
namespace of , this would result in:
Currently working on argument_data
Trace (last most recent call):
File "~/main1.py", line 6, in <module>
some_module1.random_function('argument_data')
File "~/some_module1.py", line 4, in random_function
some_internal_variable = eval(erstes_argument)
File "<string>", line 1, in <module>
NameError: Name "argument_data" is not defined
Now consider the hypothetical use of aget_identifier_name_missing_function()
which would behave as described above.
Here is a dummy Python 3.0 code: .
# principal2.py
import some_module2
some_dictionary_1 = { 'definition_1':'text_1',
'definition_2':'text_2',
'etc. and so forth.' }
some_other_dictionary_2 = { 'key_3':'value_3',
'key_4':'value_4',
'etc. and so forth.' }
#
# more stuff like that
#
some_other_dictionary_n = { 'random_n':'random_n',
'etc. and so forth.' }for each_my_dictionaries in (any_dictionary_1,
some_other_dictionary_2,
...,
some_other_dictionary_n ):
some_module2.some_function(each_of_my_dictionaries)
# algun_modulo2.py
def some_function(a_dictionary_object):
für _clave, _valor und a_dictionary_object.items():
print(get_indentifier_name_missing_function(a_dictionary_object) +
" " +
string (_key) +
" = " +
string (_value) )
######
The expected results would be:
some_dictionary_1 definition_1 = text_1
some_dictionary_1 definition_2 = text_2
some_dictionary_1 etc = etc .
some_other_dictionary_2 key_3 = value_3
some_other_dictionary_2 key_4 = value_4
some_other_dictionary_2 etc = etc .
......
......
......
some_other_dictionary_n random_n = random_n
some_other_dictionary_n etc = etc .
unfortunately,get_identifier_name_missing_function()
You would not see the names of the 'original' identifiers (any_dictionary_
,other_dictionary_2
,some_other_dictionary_n
). I would only see thema_dictionary_object
identifier name.
So the actual result would be:
a_dictionary_object definition_1 = text_1
a_dictionary_object definition_2 = texto_2
a_dictionary_object etc = etc.
a_dictionary_object chave_3 = valor_3
a_dictionary_object clave_4 = valor_4
a_dictionary_object etc = etc.
......
......
......
a_dictionary_object random_n = random_n
a_dictionary_object etc = etc.
So vice versaEvaluation()
The function is not that useful in this case.
Currently you would need to do the following:
# main2.py as above except:for each_one_of_my_name_dictionaries in('some_dictionary_1',
'another_dictionary_2',
'...',
'some_other_dictionary_n'):
some_module2.some_function( { each_one_of_my_dictionaries_names :
eval(any_one_of_my_dictionary_names) } )
# algun_modulo2.py
def some_function(a_dictionary_name_object_container):
para _dictionary_name, _dictionary_object em a_dictionary_name_object_container.items():
für _key, _value in _dictionary_object.items():
print(str(_dictionary_name) +
" " +
string (_key) +
" = " +
string (_value) )
######
Complete:
- Python only passes memory addresses as arguments to functions.
- Strings representing the name of an identifier can only be referred to by the actual identifier
Evaluation()
Function if the name identifier is available in the current namespace. - A hypothetical reversal of
Evaluation()
function, it wouldn't make sense in cases where the calling code doesn't directly "see" the name of the identifier. For example. within each called function. - Currently you need to pass a function:
- the string representing the name of the identifier
- the real identifier (memory address)
This can be achieved by passing both'corda'
mieval('string')
at the same time as the called function. I think this is the most "general" way to solve this chicken egg problem in any function, module and namespace without using corner case solutions. The only downside is usingEvaluation()
Feature that can easily lead to unsafe code. Care should be taken not to feed themEvaluation()
work with almost anything, especially unfiltered external input data.
How to convert a string to a variable name in Python
You can enter the variables directlyglobal
:
x = ['recursive1','recursive2']to varname in x:
globals()[Variablenname] = 123
Print (Source1)
#123
This allows you to createj
as stated in the question.
Just because it's possible doesn't mean it should be done that way. Without knowing the details of the problem to solve, it's difficult to give better advice, but there might be a better way to get what you're looking for.
Update: In a comment, @mozway raised some concerns about the above, one of which was thisj
It is not changed if, for example, Function2 is changed. For example:
x = ['recursive1','recursive2']to varname in x:
globals()[Variablenname] = 123
y = [Resource1, Resource2]
print(s)
#[123, 123]
Feature2 = 456
print(s)
#[123, 123]
This seems useful, although I got similar behavior myself with the regular syntax:
Resource1 = 123
Feature2 = 123
y = [Resource1, Resource2]
print(s)
#[123, 123]Feature2 = 456
print(s)
#[123, 123]
How to convert a string to a valid variable name in Python?
According to Python, an identifier is a letter or underscore followed by an unlimited sequence of letters, numbers, and underscores:
import rightFinal cleaning(s):
# Remove invalid characters
s = re.sub('[^0-9a-zA-Z_]', '', s)
# Remove leading characters until we find a letter or underscore
s = re.sub('^[^a-zA-Z_]+', '', s)
returns
Use like this:
>>> limpiar(' 32v2 g #Gmw845h$W b53wi ')
'v2gGmw845hWb53wi'
Convert a string to pre-existing variable names
As mentioned in the StackOverflow questionConfigParser local override, you are looking forEvaluation()
:
print eval('self.post.id') # Print a value of self.post.id
How to use a string value as a variable name in Python?
I don't understand exactly what you're trying to achieve with this, but it can be done withEvaluation
. I do not recommend using itEvaluation
However. It would be better if you finally tell us what you want to achieve.
>>> Karamell = ['a','b','c']
>>> fruit = ['d','e','f']
>>> Boot = ['g','h','i']
>>> name = 'fruit'
>>> evaluate(name)
['d', 'e', 'f']
EDIT
See the other answer by Sнаđошƒаӽ. There will be a better way.Evaluation
it poses a security risk and I do not recommend its use.
How do I convert a string to a variable name?
Here is a suitable solution that matches what you are trying to do (which I believe is letter indexing) using dictionaries:
Result = {}
ord = input() # Why are you calling this variable ord?
count = 1
for i in order:
if not in the result:
result[i] = []
result[i].attachment(count)
count += 1
Print (Result)
No Vars, no locals, noperishwith an uncertain context. It's no problem if someone writesUE
on your input and other similar problems. Everything safe and easy. It can be further simplified with defaultdict.
As a side note: forget about the existence of vars/locals/globals and similar objects. I've never had to use them even though I've been programming in Python for a decade. This is interesting when you write crazy code like a Python debugger. Otherwise it is not necessary. And these are swords that will cut you unless you are a samurai.
Related topics
Remove a column from a pandas dataframe
Permanently adding a directory to Pythonpath
Aggregation in Pandas
Word delimitation with words beginning or ending with special characters produces unexpected results
Equivalent to the 'Cd' shell command to change the working directory
Change a character in a string
Difference between map, applymap and apply methods in pandas
How to add floating annotations to a chart
What is the output of % in Python?
How to add new keys to a dictionary
Python Multiprocessing Pickling Error: Pickle ≪Enter 'Function'≫ cannot be executed
Identify groups of consecutive numbers in a list
What exactly is the current working directory?
The pip installation fails with "Connection Error: [Ssl: Certificate_Verify_Failed] Certificate Verify Failed (_Ssl.C:598)".
How to change the date and time format in pandas
Understanding the "is" operator
Iterate a list as a (current, next) pair in Python
Asynchronous requests with Python requests
FAQs
How do I turn a string into a variable name? ›
Method 1: Using assign() function
We can assign character string to variable name by using assign() function. We simply have to pass the name of the variable and the value to the function.
Declaring strings as variables can make it easier for us to work with strings throughout our Python programs. To store a string inside a variable, we need to assign a variable to a string. In this case let's declare my_str as our variable: my_str = "Sammy likes declaring strings."
Can a string be a variable name? ›A string variable is a variable that holds a character string. It is a section of memory that has been given a name by the programmer. The name looks like those variable names you have seen so far, except that the name of a string variable ends with a dollar sign, $. The $ is part of the name.
How do you give a variable a name in Python? ›- A variable name must start with a letter or the underscore character.
- A variable name cannot start with a number.
- A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
- Variable names are case-sensitive (age, Age and AGE are three different variables)
A variable name must start with a letter or an underscore character (_) A variable name cannot start with a digit. A variable name can only contain alpha-numeric characters and underscores ( a-z, A-Z , 0-9 , and _ ) Variable names are case-sensitive (age, Age and AGE are three different variables)
How do you change input to variable in Python? ›Use the input() function to get Python user input from keyboard. Press the enter key after entering the value. The program waits for user input indefinetly, there is no timeout. The input function returns a string, that you can store in a variable.
How do you store a string in a variable? ›For example, if we wanted to store the string "Quackers" into a variable named pet, we would write it like this: string pet = "Quackers"; This line declares a variable named pet with the type string and stores the string "Quackers" inside of it.
What is Vars () in Python? ›vars() function in Python
This is an inbuilt function in Python. The vars() method takes only one parameter and that too is optional. It takes an object as a parameter which may be can a module, a class, an instance, or any object having __dict__ attribute. Syntax: vars(object)
When Python wants to store text in a variable, it creates a variable called a string. A string's sole purpose is to hold text for the program. It can hold anything—from nothing at all (") to enough to fill up all the memory on your computer.
Can I get variable name in Python? ›python-varname is not only able to detect the variable name from an assignment, but also: Retrieve variable names directly, using nameof. Detect next immediate attribute name, using will. Fetch argument names/sources passed to a function using argname.
How do you get the variable name from a value in Python? ›
To get a variable name as a string in Python we use the iteritems() or the items() method. This is basically a process of searching for a variable name with the help of a reverse approach. Parameters: It is important to know that this method does not take any parameters.
How do you print the name of a variable in Python? ›This is done by using the “+” character between two variables or strings. This way we can use Python to print variable values along with the string.
What does name () do in Python? ›The __name__ variable (two underscores before and after) is a special Python variable. It gets its value depending on how we execute the containing script. Sometimes you write a script with functions that might be useful in other scripts as well. In Python, you can import that script as a module in another script.
What is an example of a variable name? ›The following are examples of valid variable names: age, gender, x25, age_of_hh_head.
What are good variable names in Python? ›- Be clear and concise.
- Be written in English. ...
- Not contain special characters. ...
- Not conflict with any Python keywords, such as for , True , False , and , if , or else .
Declaring (Creating) Variables
type variableName = value; Where type is one of Java's types (such as int or String ), and variableName is the name of the variable (such as x or name). The equal sign is used to assign values to the variable.
Python has no command for declaring a variable. A variable is created the moment you first assign a value to it.
How to convert string to int Python? ›To convert, or cast, a string to an integer in Python, you use the int() built-in function. The function takes in as a parameter the initial string you want to convert, and returns the integer equivalent of the value you passed. The general syntax looks something like this: int("str") .
Can you change a variable Python? ›Some values in python can be modified, and some cannot. This does not ever mean that we can't change the value of a variable – but if a variable contains a value of an immutable type, we can only assign it a new value. We cannot alter the existing value in any way.
How to convert string to variable in Java? ›Example 1: Java Program to Convert string to int using parseInt() In the above example, we have used the parseInt() method of the Integer class to convert the string variables into the int . Here, Integer is a wrapper class in Java.
How to use a string as a variable name Java? ›
- String Variables in Java. String variables are variables used to hold strings.
- Syntax. modifier String stringName = "String to store";
- Notes. A string is technically an object, so its contents cannot be changed (immutable). ...
- Example. String name = "Anthony"; System.out.println("Hello, your name is " + name);
By new keyword : Java String is created by using a keyword “new”. For example: String s=new String(“Welcome”); It creates two objects (in String pool and in heap) and one reference variable where the variable 's' will refer to the object in the heap.
How do you assign a variable to a string value? ›String assignment is performed using the = operator and copies the actual bytes of the string from the source operand up to and including the null byte to the variable on the left-hand side, which must be of type string. You can create a new variable of type string by assigning it an expression of type string.
How do you convert a string to a number in Python? ›To convert, or cast, a string to an integer in Python, you use the int() built-in function. The function takes in as a parameter the initial string you want to convert, and returns the integer equivalent of the value you passed. The general syntax looks something like this: int("str") .
How to convert string into int Python? ›To convert a string to integer in Python, use the int() function. This function takes two parameters: the initial string and the optional base to represent the data. Use the syntax print(int("STR")) to return the str as an int , or integer.
What is string variable example? ›Example: Zip codes and phone numbers, although composed of numbers, would typically be treated as string variables because their values cannot be used meaningfully in calculations. Example: Any written text is considered a string variable, including free-response answers to survey questions.
How do you create a variable called name of type string and assign it with value? ›- Create a variable called name of type string and assign it the value "John": string name = "John"; Console. ...
- Create a variable called myNum of type int and assign it the value 15: int myNum = 15; Console. ...
- int myNum; myNum = 15; Console.
You can assign a new value to a variable in the same way you originally assigned a value to it: Using the assignment operator, = .
How do I convert a string back to an object? ›To convert the string back to object, we'll use the opposite of JSON. stringify , which is JSON. parse .
What is str () in Python? ›Python has a built-in string class named "str" with many handy features (there is an older module named "string" which you should not use). String literals can be enclosed by either double or single quotes, although single quotes are more commonly used.
How do you assign a variable in Python? ›
The assignment operator, denoted by the “=” symbol, is the operator that is used to assign values to variables in Python. The line x=1 takes the known value, 1, and assigns that value to the variable with name “x”. After executing this line, this number will be stored into this variable.