How To Split A String By Whitespace In Python

Split a string by whitespace in python

Some methods can help split a string by whitespace in Python. Let’s learn about it with the explanation and examples below.

Split a string by whitespace in python

To split a string by whitespace in python, you can use the split() method. The split() method returns a list of strings after having split the strings based on the given delimiters.

Some effects of the split() method:

  • In some cases, we need to split large strings into small strings.
  • Whitespace has defaulted if there are no delimiters in split().
  • Analysis and results are made more accessible.
  • Can decode encrypted strings.

Syntax:

str.split(sep, maxsplit)

Parameter:

  • sep(separator): is the delimiter used to split the output string into substrings. The default is whitespace.
  • maxsplit: is the maximum number of splits. If not specified, Python will interpret it as an infinite number of splits.

Let’s take a look at a few ways to separate the following:

The shortened ‘split()’ method

Syntax: str.split()

Example:

print('My name is John'.split())

Output:

['My', 'name', 'is', 'John']

The ‘split()’ method to specify the separator character

Syntax: str.split(sep)

Example:

print('My name is John'.split(' '))

Output:

['My', 'name', 'is', 'John']

Note: You can use ‘sep’ as a delimiter or a delimiter string.

The ‘split’ method specifies the maximum split frequency

Syntax: str.split(sep, maxsplit)

Example:

print('1 2 3 4 5'.split(" ", 5)) # ['1', '2', '3', '4', '5']
print('My name John'.split(" ", 2)) # ['My', 'name', 'John']

Output:

['1', '2', '3', '4', '5']
['My', 'name', 'John']

In the above example, ‘maxsplit’ equals the string length.

Note:  in case ‘maxsplit’ is larger than the string length, Python can only cut out the number of strings equal to the length of the string.

Summary

Our tutorial has guided you through different ways to split a string by whitespace in Python. We always hope this tutorial is helpful to you. If you have any questions, please let us know by leaving your comment in this tutorial. Thank you.

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *