How to split delimited string in Python?

Earlier I wrote about several methods to split delimited string in SQL Server. Now we will see how to split delimited string in Python. To split a string based on a delimiter and store the result in a list, we can use the str.split() method. In the below example, there is a long string “Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday” which has names of week days separated by a delimiter comma. In order to split this long string to a list of week names, use the str.split() method providing the delimiter.

week_names = "Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday"
 
week_name_list = week_names.split(",")

print("\n", week_name_list, "\n")
split delimited string in Python

Split string with space as delimiter

For splitting a string based on the space character as a delimiter is similar to the above example. The only difference is, we don’t need specify the delimiter in the str.split() method method.

week_names = "Sunday Monday Tuesday Wednesday Thursday Friday Saturday"
 
week_name_list = week_names.split()

print("\n", week_name_list, "\n")

If you are interested, you can read about how this split technique is used to extract numbers form a string.

Reference

Related Articles & Tools

Leave your thoughts...

This site uses Akismet to reduce spam. Learn how your comment data is processed.