Python string split() example

Python example to split string into fields using the delimiters in the string.

1. Split string.split() method

Easiest way to split a string using a delimiter is using string.split( delimiter ) function.

>>> str = 'how,to,do,in,java'

>>> str.split(',')			# split string using delimiter comma

['how', 'to', 'do', 'in', 'java'] #Output

2. Split string with multiple delimiters

The split() method of string objects is really meant for very simple cases, and does not allow for multiple delimiters or account for possible whitespace around the delimiters.

In cases when you need a bit more flexibility, use the re.split() method:

>>> import re

>>> line = 'how to; do, in,java,      dot, com'

>>> re.split(r'[;,\s]\s*', line)	# split with delimiters comma, semicolon and space 
					# followed by any amount of extra whitespace.

['how', 'to', 'do', 'in', 'java', 'dot', 'com']

When using re.split(), you need to be a bit careful should the regular expression pattern involve a capture group enclosed in parentheses. If capture groups are used, then the matched text is also included in the result.

For example, watch what happens here:

>>> import re

>>> line = 'how to; do, in,java,      dot, com'

>>> re.split(r'(;|,|\s)\s*', line)	# split with delimiters comma, semicolon and space 
									# followed by any amount of extra whitespace.

['how', ' ', 'to', ';', 'do', ',', 'in', ',', 'java', ',', 'dot', ',', 'com']

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.