Python (Scripting) - Convert string to list using split

by
Jeremy Canfield |
Updated: February 18 2024
| Python (Scripting) articles
split can be used to convert a string into a list. By default, split will be done using whitespace.
#!/usr/bin/python3
foo = "data more data even more data"
bar = foo.split()
print(f"foo = {foo}")
print(f"bar = {bar}")
Running this script should output the following.
foo = "data more data even more data"
bar = ['data', 'more', 'data', 'even', 'more', 'data']
In this example, the foo variable is split at each comma.
#!/usr/bin/python3
foo = "data,more data,even more data"
bar = foo.split(',')
print(f"foo = {foo}")
print(f"bar = {bar}")
Running this script should output the following.
foo = "data,more data,even more data"
bar = ['data', 'more data', 'even more data']
In this example, since there is no delimiter that can be used to split foo, the following can be used.
#!/usr/bin/python3
foo = "ABCD"
bar = []
bar[:0] = foo
print(f"foo = {foo}")
print(f"bar = {bar}")
Which should produce the following.
foo = "ABCD"
bar = ['A', 'B', 'C', 'D']
In this example, each item will have a unique index number.
- data = 0
- more data = 1
- even more data = 2
Here is how you can print a item using an index number.
#!/usr/bin/python3
foo = "data,more data,even more data"
bar = foo.split(',')
try:
bar[1]
except Exception as exception:
print(f"got the following exception when trying bar[1] - {exception}")
else:
print(bar[1])
Running this script should output the following, the value of index 1.
more data
Did you find this article helpful?
If so, consider buying me a coffee over at