Python | Split String into Variables

πŸš€Summary: Split the given string using the split() function and then unpack the items of the list returned by the split method into different variables.

Minimal Example

txt = 'one,two,three'
x,y,z = txt.split(',')
print(x,y,z)

# one two three

Problem Formulation

πŸ“Problem: Given a string. How will you split the string and then store the split strings into different variables?

Example 1

# Given String
text = 'Hello World'

# Expected Output:
Number of split strings:  2
x = Hello
y = World

In the above problem, the given string is simple and it is evident that two variables are required to store the split strings. Therefore, you need to create two variables to store the two split substrings.

Example 2

# Given String
text = 'KBDNM-R8CD9-RK366-WFM3X-C7GXK'
# Expected Output:
key_1 = KBDNM
key_2 = R8CD9
key_3 = RK366
key_4 = WFM3X
key_5 = C7GXK

In the above problem, the delimiter used to split the string is “-“. The number of variables here is hard to find (say if its an even longer string!). How will you split the string in such a case and store them into the different variables?


Scenario 1

Let’s have a look at the solution to example 1.

Solution: As the number of variables is fixed, i.e., we have a fair idea about the number of variables required, you have to use the split() function on the given string which splits the given string into two items and stores them in a list. Unpack these values into two variables such that the first item will be stored in one variable while the second item will be stored in another variable.

Code:

# Given String
text = 'Hello World'
x, y = text.split()
print(x)
print(y)

# OUTPUT
# Hello
# World

Well! That was easy. Let’s dive into the more complex problem.

Scenario 2

✨Method 1: Split and Create Dictionary

Approach: The idea here is to split the list using β€œ-” as the delimiter and then find the length of the resultant list returned by the split function. Then use this length to create another list containing all the variable names as items within it. This can be done with a simple for loop. Thus, you will effectively have two lists – one that stores the split strings and another that stores the variable names that will store the split strings.

You can then create a dictionary out of the two lists such that the keys in this dictionary will be the items of the list containing the variable names and the values in this dictionary will be the items of the list containing the split strings.

Code:

# Given String
text = 'KBDNM-R8CD9-RK366-WFM3X-C7GXK'
# splitting the string using - as a separator
res = text.split('-')

# Naming and storing variables and values
name = []
for i in range(1, len(res)+1):
    name.append('key_' +str(i))
d = dict(zip(name, res))
for key, value in d.items():
    print(key, "=", value)

Output:

key_1 = KBDNM
key_2 = R8CD9
key_3 = RK366
key_4 = WFM3X
key_5 = C7GXK

🌐Recommended read: How to Convert Two Lists Into A Dictionary

✨Method 2: Use __dict__

Almost all modules have a special attribute known as __dict__ which is a dictionary containing the module’s symbol table. It is essentially a dictionary or a mapping object used to store an object’s (writable) attributes.

So, you can create a class and then go ahead create an instance of this class which can be used to set different attributes. Once you split the given string and also create the list containing the variable names (as done in the previous solution), you can go ahead and zip the two lists and use the setattr() method to assign the variable and their values which will serve as the attributes of the previously created class object. Once, you have set the attributes (i.e. the variable names and their values) and attached them to the object, you can access them using the built-in __dict__ as object_name.__dict__

Code:

# Given String
text = 'KBDNM-R8CD9-RK366-WFM3X-C7GXK'
# splitting the string using - as a separator
res = text.split('-')
# length of split string list
x = len(res)
# variable creation and value assignment
name = []
for i in range(1, x + 1):
    name.append('key_' + str(i))
class Record():
    pass
r = Record()
for name, value in zip(name, res):
    setattr(r, name, value)
for key, value in r.__dict__.items():
    print(key, "=", value)

Output:

key_1 = KBDNM
key_2 = R8CD9
key_3 = RK366
key_4 = WFM3X
key_5 = C7GXK

✨Method 3: Use globals

globals() function returns a dictionary containing all the variables in the global scope with the variable names as the key and the value assigned to the variable will be the value in the dictionary. You can reference this dictionary and add new variables by string name (globals()[‘a’] = ‘b’ sets variable a equal to “b”).

Since global returns a dictionary containing all the variables in the global scope, a workaround to get only the variables we assigned is to extract the last β€œN” key-value pairs from this dictionary where β€œN” is the length of the split string list.

Code:

# Given String
text = 'KBDNM-R8CD9-RK366-WFM3X-C7GXK'
# splitting the string using - as a separator
res = text.split('-')
# length of split string list
x = len(res)

name = []
for i in range(1, x + 1):
    name.append('key_' + str(i))
for idx, value in enumerate(res):
    globals()["key_" + str(idx + 1)] = value

x = 0
for i in reversed(globals()):
    print(i, "=", globals()[i])
    x = x+1
    if x == 5:
        break

Output:

key_5 = C7GXK
key_4 = WFM3X
key_3 = RK366
key_2 = R8CD9
key_1 = KBDNM

⚠️Caution: This solution is not recommended unless this is the only option left. I have mentioned this just because it solves the purpose. However, it is certainly not the best way to approach the given problem.

Conclusion

I hope the solutions mentioned in this article have helped you. Please subscribe and stay tuned for more interesting articles and solutions in the future. Happy coding! πŸ™‚