Seperate strings from array that have whitespace from those that dont have whitespaces in python

Viewed 149

I have an array that has strings in it and I want to make 2 new arrays, first array is the one that will have items from first list that have whitespaces and second array that has those who don't:

array = ["something", "something with space", "something2", "something with space 2"]

First:

noWhitespaceCharacters = ["something", "something2"]

Second:

hasWhitespaceCharacters = ["something with space", "something with space 2"]
3 Answers

just check if there is whitespace or not by in keyword

array = ["something", "something with space", "something2", "something with space 2"]
nows=[i for i in array if " " in i]
ws = [i for i in array if " " not in i]

nows means no white space, ws means white space

You could try to split every words. The basic operator for .split() method is the whitespace, indeed. If the string is sub-divided into more pieces, it means it contains whitespaces.

no_white  = []
white = []

for val in array:
    if len(val.split()) > 1:
        white.append(val)
    else:
        no_white.append(val)

I assume first array is the one that will have items from first list that have whitespaces and second array that has those who don't has precedence over your example. You might use set arithmetic and built-in string module following way

import string
ws = set(string.whitespace)
arr = ["something", "something with space", "something2", "something\n\with\nnewline"]
without_ws = [i for i in arr if not ws.intersection(i)]
with_ws = [i for i in arr if ws.intersection(i)]

Explanation: .interesction provide common elements

Related