HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Python / Python string split() example

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?

Let us know if you liked the post. That’s the only way we can improve.
TwitterFacebookLinkedInRedditPocket

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Comments are closed on this article!

Search Tutorials

Python Inbuilt Functions

  • Python abs()
  • Python all()
  • Python any()
  • Python ascii()
  • Python bin()
  • Python input()
  • Python print()

Python String Functions

  • Python String endswith()
  • Python String split()
  • Python String startswith()

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Sealed Classes and Interfaces