Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Adding whitespaces around each element of a list of lists python

I want to add whitespaces around each element within a list of lists

data = [["hello", "world"], ["python", "is", "cool"]]
-->
data = [[" hello ", " world "], [" python ", " is ", " cool "]]
data_new = ["hello world", "python is cool"]
data_new2 = [x.split(" ") for x in data_new]
--> [["hello", "world"], ["python", "is", "cool"]]
data_new2 = [' {0} '.format(word) for elem in data_new2 for word in elem]
print(data_new2[:10])
--> [" hello ", " world ", " python ", " is ", " cool "]

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You don’t need to split, use a nested list comprehension (here with a f-string):

data = [["hello", "world"], ["python", "is", "cool"]]

data2 = [[f' {x} ' for x in l] for l in data]

Output:

[[' hello ', ' world '], [' python ', ' is ', ' cool ']]

Alternative input:

data = ["hello world", "python is cool"]

data2 = [[f' {x} ' for x in s.split()] for s in data]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading