
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Convert String to List of Words in Python
Strings are one of the most commonly used data types. In this article, we are going to find out how to convert a string to a list of words in Python.
Converting the string into a list is helpful when dealing with user inputs or when we want to manipulate individual words in a string. Python provides several ways to achieve this. Let's explore them one by one.
Using Python str.split() Method
Python str.split() method accepts a separator as a parameter, splits the string at the specified separator, and returns the result as a list. If we use the split() method without any arguments, it splits the string at every whitespace character and returns a list where each element is a word from the original string.
Syntax
Following is the syntax of the Python str.split() method -
str.split(separator, maxsplit)
Example 1
Let's look at the following example, where we are going to consider the basic usage of the split() method.
str1 = "Welcome To TutorialsPoint" result = str1.split() print(result)
The output of the above program is as follows -
['Welcome', 'To', 'TutorialsPoint']
Example 2
Consider another scenario, where we are passing the comma(,) as the argument to the split() method -
str1 = "Activa,Vespa,Pept,Access" result = str1.split(',') print(result)
The output of the above program is as follows -
['Activa', 'Vespa', 'Pept', 'Access']
Example 3
In the following example, we are going to use the list comprehension along with the split() method to remove the unwanted empty strings.
str1 = "Hi Hello Vanakam " result = [x for x in str1.split() if x] print(result)
The output of the above program is as follows -
['Hi', 'Hello', 'Vanakam']
Using re.split() Method
The Python re.split() method is used to split a string by the occurrence of a specified regular expression pattern.
Here, we are using the regular expression '\d+' to match the digits. The re.split() method splits the string at every occurrence of the digits, returning the list of words that are separated by digits.
Syntax
Following is the syntax of Python re.split() method -
re.split(pattern, string, maxsplit=0, flags=0)
Example
Following is an example where we are going to use the regex pattern to convert the string to a list of words.
import re str1 = "Audi 1123 Benz 234 Ciaz" result = re.split(r'\d+', str1) print(result)
The following is the output of the above program -
['Audi ', ' Benz ', ' Ciaz']