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 8000+ Awesome Developers, Like YOU!

Leave a Comment

About HowToDoInJava

This blog provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions, and frequently asked interview questions.