I want to know how to split a singular element of my list into multiple different elements. For example:
list=['My phone is cracked']
I want to make it into this:
list=['My','phone','is','cracked']
I want to know how to split a singular element of my list into multiple different elements. For example:
list=['My phone is cracked']
I want to make it into this:
list=['My','phone','is','cracked']
list=['My phone is cracked']
list = list[0].split(" ")
print(list)
This will print your desired output.
the reason why there is a [0]
after the list
is because split
only works on strings so you will have to take out the first value in the array and that will treat it like an array.
Hope this helps!:)
I am assuming that the ask is to iterate through the list and split the element into multiple elements using ' ' if exists, else element as is.
So
['My phone is cracked', 'new phone', 'collection']
becomes
['My', 'phone', 'is', 'cracked', 'new', 'phone', 'collection']
This is how you can do that:
list1 = ['My phone is cracked', 'new phone', 'collection']
new_list1 = [y for x in list1 for y in x.split(' ')]
You can use the split() method (https://docs.python.org/3.5/library/stdtypes.html#str.split).
list[0].split()