1

Can anyone help me with a list comprehension to split a string into a nested list of words and characters? i.e:

mystring = "this is a string"

Wanted ouput:

[['t','h','i','s'],['i','s'],['a'],['s','t','r','i','n','g']]

I've tried the following, but it doesnt split 'x' into nested list:

mylist = [x.split() for x in mystring.split(' ')]
print(mylist)
[['this'],['is'],['a'],['string']]
  • Possible duplicate of [How do I convert string characters into a list?](https://stackoverflow.com/questions/10610158/how-do-i-convert-string-characters-into-a-list) – mkrieger1 Oct 01 '18 at 21:09

4 Answers4

4
[list(x) for x in mystring.split(' ')]
ForceBru
  • 43,482
  • 10
  • 63
  • 98
jwzinserl
  • 427
  • 1
  • 3
  • 7
2

You can use a nested list comprehension:

[[j for j in i] for i in mystring.split()]

Yields:

[['t', 'h', 'i', 's'], ['i', 's'], ['a'], ['s', 't', 'r', 'i', 'n', 'g']]
rahlf23
  • 8,869
  • 4
  • 24
  • 54
1

You need list(x) instead of x.split():

[list(x) for x in mystring.split()]
V13
  • 853
  • 8
  • 14
0

Slightly similar to other answers

map(list,mystring.split(" "))
mad_
  • 8,121
  • 2
  • 25
  • 40