Split string by whitespace in python

featured Image

In this post, we will learn how to split a string by spaces in python.

To split a string by whitespace in python we can use the split() method. It splits a string and returns us a list containing the individual words from the string.

Syntax:

str.split(separator)

We can specify the separator in the split method. By default, the separator is any whitespace (' ').

Split string in python

Let’s see an example of the str.split() method

str = "I am a programmer"
split_str = str.split()
print(split_str)

The output is:

['I', 'am', 'a', 'programmer']

Here, we have called the split() method on the string. And since we have not passed any separator in the method, so by default, it split the given string by whitespace and returned us a list.

We can also use Regular expressions for this task too.

Using RegEx to split a string

To use RegEx in python we have to import the Regular Expression module (re). It also provides a pre-defined split() method that we can use to split a string by its spaces.

Example:

import re

str = 'I am a programmer'
split_str = re.split('s+', str)

print(split_str) // ['I', 'am', 'a', 'programmer']

Here, re.split() splits the string into a list of substrings.

s it represents whitespace in regular expression.

The + sign is use to match all whitespaces in the given string.

Even though the regular expression method is overkill for such a small task. But it’s still better to know.


Related Topics:

Split String and get the first element using python

How to split a list into multiple lists using Python

Replace a character in String by index in Python

Python – Check if a string is Empty or Not

Python – Remove Newline From Strings (3 Ways)

How to Append String in Python

Convert a string into an integer or float using Python

Related Posts

merge json files in python

How to merge JSON files in python

JSON (JavaScript Object Notation) is a data format used for storing, transferring, and visualizing data. Its simple structure of key:value pairs and array data types makes JSON an easy and…

Read more
Install python pip in ubuntu

How to Install Pip(pip3) in Ubuntu Linux 22.04

Pip is a package manager for Python that allows you to install and manage additional Python packages that are not part of the Python standard library. Pip makes it easy…

Read more
featured Image

How to Write If-Else Statements in One Line in Python

If-else statements are a fundamental concept in Python and other programming languages. They allow you to execute different blocks of code based on whether a condition is true or false….

Read more

Leave a Reply

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