close

How to split strings inside a list by whitespace characters

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to split strings inside a list by whitespace characters in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to split strings inside a list by whitespace characters?

  1. How to split strings inside a list by whitespace characters?

    You can use simple list comprehension, like:
    newlist = [word for line in mylist for word in line.split()]

  2. split strings inside a list by whitespace characters

    You can use simple list comprehension, like:
    newlist = [word for line in mylist for word in line.split()]

Method 1

You can use simple list comprehension, like:

newlist = [word for line in mylist for word in line.split()]

This generates:

>>> [word for line in mylist for word in line.split()]
['this', 'is', 'a', 'string', 'of', 'text', 'this', 'is', 'a', 'different', 'string', 'of', 'text', 'and', 'for', 'good', 'measure', 'here', 'is', 'another', 'one']

Method 2

You could just do:

words = str(list).split()

So you turn the list into a string then split it by a space bar. Then you can remove the /n’s by doing:

words.replace("/n", "")

Or if you want to do it in one line:

words = str(str(str(list).split()).replace("/n", "")).split()

Just saying this may not work in python 2

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read