How to Split a String using delimiter in Python


There are multiple ways in which we can split a string in Python based on the delimiter, let's take a look at some of them with examples.


Example 1: Using the split() function

>>> string_data = "1,2,3,4,5,6,7,8,9,10"
>>> splitted_string = string_data.split(",")
>>> print(splitted_string)
['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
>>> 
>>> print(type(splitted_string))
<class 'list'>
>>> 

The most common delimiters that one comes across when parsing data line by line as strings in files are,

DelimiterSymbolDescription
Comma,Used to separate values in CSV files
Tab\tUsed as a delimiter in TSV files
Pipe|Commonly used in data interchange formats
Semicolon;Often used in European CSV files
Colon:Used in some data formats and configurations
SpaceSeparates values in space-delimited files
Hyphen-Used in certain data representations
Underscore_Occasionally used as a separator
Dot.Used in some file extensions

You can simply use the symbol like these as an argument to the split function.



Let's take another example where data is separated by pipe as a delimiter.

Example:
>>> string_data = "1|2|3|4|5|6|7|8|9|10"
>>> splitted_string = string_data.split("|")
>>> print(splitted_string)

['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']

Reference documentation:

Python split() method documentation


Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap