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
  • 41,233
  • 10
  • 61
  • 89
jwzinserl
  • 347
  • 1
  • 2
  • 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,613
  • 3
  • 19
  • 49
1

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

[list(x) for x in mystring.split()]
V13
  • 647
  • 6
  • 12
0

Slightly similar to other answers

map(list,mystring.split(" "))
mad_
  • 7,844
  • 2
  • 22
  • 37