how to split each word in a string in a seperate list

  • A+
Category:Languages

How would I go about splitting each word in a string in a separate string? if I, for example, have this code

s = "It sure is a nice day today" l = list(s) 

This would return ['I', 't', ' ', 's', 'u', 'r', 'e', ' ', 'i', 's', ' ', 'a', ' ', 'n', 'i', 'c', 'e', ' ', 'd', 'a', 'y', ' ', 't', 'o', 'd', 'a', 'y'] instead, I's like to have it return seperate lists like so:

['I', 't'] ['s', 'u', 'r', 'e'] ['i', 's'] ['a'] ['n', 'i', 'c', 'e'] ['d', 'a', 'y'] ['t', 'o', 'd', 'a', 'y'] 

And if possible store them in seperate lists instead of simply printing them.

 


Well this looks like a list of lists, since you need some datastructure to store these sublist in.

For example:

s = "It sure is a nice day today" result = [list(si) for si in s.split()] 

This then generates:

>>> result = [list(si) for si in s.split()] >>> result [['I', 't'], ['s', 'u', 'r', 'e'], ['i', 's'], ['a'], ['n', 'i', 'c', 'e'], ['d', 'a', 'y'], ['t', 'o', 'd', 'a', 'y']] 

Of course you can also store these sublists in a tuple, etc. But somehow you will have to wrap these into a collection that can store lists.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: