Split string by whitespace in python
Find out how to split a string by whitespace using split() method in python. The split method split a string and returns a list.
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:
Related Posts
How to merge JSON files in python
Learn different techniques to merge multiple JSON files in Python using built-in JSON module and Pandas library. Includes examples for combining data arrays and merging dictionaries by key.
Pytube Description and Keyword Not Showing: Solution
Solve the issue with Pytube not showing youtube description and tags in this article.
How to Fix the subprocess-exited-with-error in Python
Learn what cause the subprocess-exited-with-error in Python and also learn how to solve the error in your code.
Python Integer Division: The Floor Division Operator Explained
Article on Python Integer Division operator (//) with examples and the difference between standard division and floor division.
