How to convert a string to a list of words in python?


In this article, we are going to find out how to convert a string to a list of words in Python.

The first approach is to use the built−in method split (). This function separates a text at the delimiter we specify. The delimiter parameter is sent to the split() function, and it indicates where a text should be divided.

As a result, we must pass white space to the split() function as a delimiter. This function returns a white-space-separated modified list.

Example 1

In the example given below, we are taking a string as input and we are converting them into list of words using split() method 

str1 = "Hello Everyone Welcome to Tutoiralspoint"

print("The given string is")
print(str1)

print("Converting them into list of words")
res = str1.split()
print(res)

Output

The output of the given example is as follows −

The given string is
Hello Everyone Welcome to Tutoiralspoint
Converting them into list of words
['Hello', 'Everyone', 'Welcome', 'to', 'Tutoiralspoint']

Example 2

In the example given below, we are taking the same program as above but we are taking different input and converting that into list of words 

str1 = "Hello-Everyone-Welcome-to-Tutoiralspoint"

print("The given string is")
print(str1)

print("Converting them into list of words")
res = str1.split('-')
print(res)

Output

The output of the above example is given below −

The given string is
Hello-Everyone-Welcome-to-Tutoiralspoint
Converting them into list of words
['Hello', 'Everyone', 'Welcome', 'to', 'Tutoiralspoint']

Using re.split()

In the second method, regular expressions are used. To use the re library, import it and install it if it isn't already installed. We may use the regular expression's+' in the re.split() method after loading the re library. The regular expression and the string are sent as inputs to the re.split() method, which separates the text at the characters indicated by the regular expression.

Example

In the example given below, we are taking a string as input and we are splitting the string at whitespace using regular expressions.

import re
str1 = "Hello Everyone Welcome to Tutorialspoint"

print("The given string is")
print(str1)

print("The strings after the split are")
res = re.split('\s+', str1)
print(res)

Output

The output of the above example is as shown below −

The given string is
Hello Everyone Welcome to Tutorialspoint
The strings after the split are
['Hello', 'Everyone', 'Welcome', 'to', 'Tutorialspoint']

Updated on: 07-Dec-2022

8K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements