Skip to content
Advertisement

Python, string in format of setting variables into variables

This is probably very simple, but I can’t seem to find an answer anywhere. I have a String:

str = "A = Test,n B = 4, n C = 100"

How do I turn this into the three different variables?

This is in python 3.

Advertisement

Answer

As the structure of your string looks simple, you can use the split method with several delimiters (using the re package). You can check if a variable can be converted into an int by casting an exception. I suggest to store the variables in a dictionary after then like this:

import re 

my_string = "A = Test,n B = 4, n C = 100"
list_of_string = re.split(' |,n |, n', my_string)

my_dict = {}
for i in range(len(list_of_string)):
    if (list_of_string[i] == '='):
        try:
            my_dict[list_of_string[i - 1]] = int(list_of_string[i+1]) 
        except:
            my_dict[list_of_string[i - 1]] = list_of_string[i+1] 

print(my_dict)

output:

{'A': 'Test', 'B': 4, 'C': 100}
Advertisement