Python | Split String and Count Results

✨Summary: Split the string using split and then use len to count the results.

Minimal Example

print("Result Count: ", len('one,two,three'.split(',')))
# Result Count: 3

Problem Formulation

πŸ“œProblem: Given a string. How will you split the string and find the number of split strings? Can you store the split strings into different variables?

Example

# Given String
text = '366NX-BQ62X-PQT9G-GPX4H-VT7TX'
# Expected Output:
Number of split strings:  5
key_1 = 366NX
key_2 = BQ62X
key_3 = PQT9G
key_4 = GPX4H
key_5 = VT7TX

In the above problem, the delimiter used to split the string is “-“. After splitting, five substrings can be extracted. Therefore, you need five variables to store the five substrings. Can you solve it?


Solution

Splitting the string and counting the number of results is a cakewalk. All you have to do is split the string using the split() function and then use the len method upon the resultant list returned by the split method to get the number of split strings present.

Code:

text = '366NX-BQ62X-PQT9G-GPX4H-VT7TX'
# splitting the string using - as separator
res = text.split('-')
# length of split string list
x = len(res)
print("Number of split strings: ", x)

Now, let’s dive into the tough bit wherein you are required to store the split strings into diferent variables.

Approach 1

  • The idea here is to find the length of the resultant list containing the split strings and then use this length to create another list containing all the variable names as items within it. This can be done with the help of a simple for loop.
  • Now, you have two lists. One that stores the split strings and another that stores the variable names that will store the split strings.
  • So, you can 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. Read: How to Convert Two Lists Into A Dictionary

Code:

text = '366NX-BQ62X-PQT9G-GPX4H-VT7TX'
# splitting the string using - as separator
res = text.split('-')
# length of split string list
x = len(res)

# Naming and storing variables and values
name = []
for i in range(1, x+1):
    name.append('key_'+str(i))

d = dict(zip(name, res))
for key, value in d.items():
    print(key, "=", value)

Output:

key_1 = 366NX
key_2 = BQ62X
key_3 = PQT9G
key_4 = GPX4H
key_5 = VT7TX

Approach 2

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:

text = '366NX-BQ62X-PQT9G-GPX4H-VT7TX'
# splitting the string using - as separator
res = text.split('-')
# length of split string list
x = len(res)
print("Number of split strings: ", x)

# 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)
print(r.__dict__)

for key, value in r.__dict__.items():
    print(key, "=", value)

Output:

Number of split strings:  5
{'key_1': '366NX', 'key_2': 'BQ62X', 'key_3': 'PQT9G', 'key_4': 'GPX4H', 'key_5': 'VT7TX'}
key_1 = 366NX
key_2 = BQ62X
key_3 = PQT9G
key_4 = GPX4H
key_5 = VT7TX

Approach 3

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.

Code:

text = '366NX-BQ62X-PQT9G-GPX4H-VT7TX'
# splitting the string using - as separator
res = text.split('-')
# length of split string list
x = len(res)
print("Number of split strings: ", x)
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
print(globals())
x = 0
for i in reversed(globals()):
    print(i, "=", globals()[i])
    x = x+1
    if x == 5:
        break

Output:

Number of split strings:  5

{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x0000025775E86D00>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'C:\\Users\\SHUBHAM SAYON\\PycharmProjects\\Finxter\\Blogs\\Finxter.py', '__cached__': None, 'text': '366NX-BQ62X-PQT9G-GPX4H-VT7TX', 'res': ['366NX', 'BQ62X', 'PQT9G', 'GPX4H', 'VT7TX'], 'x': 5, 'name': ['key_1', 'key_2', 'key_3', 'key_4', 'key_5'], 'i': 5, 'idx': 4, 'value': 'VT7TX', 'key_1': '366NX', 'key_2': 'BQ62X', 'key_3': 'PQT9G', 'key_4': 'GPX4H', 'key_5': 'VT7TX'}

key_5 = VT7TX
key_4 = GPX4H
key_3 = PQT9G
key_2 = BQ62X
key_1 = 366NX

Explanation: 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"), however this is generally a terrible thing to do.

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.

Conclusion

I hope the solutions mentioned in this tutorial have helped you. Please stay tuned and subscribe for more interesting reads and solutions in the future. Happy coding!