Split first element of python list with space

I have a simple list as below:

lst = ['11 12221/n']

I want to split the first item in a list, as shown below:

['11', '12221']

It seems relatively simple to me, but I can't get it to work. My first approach was to do:

lst[0].split() 

but when I print the list, there are no changes. So I tried:

newLst=[]

for x in lst:
    newList.append(x.split())

But from this I get

[['11', '12221\n']]

I think that I should fundamentally understand the misunderstanding of the list, can someone explain why my code did not work and how it should be done?

thank

+5
source share
4 answers

You can do it like:

lst = ['11 12221\n']

lst = lst[0].split()

list[0] '11 12221\n', split() lst, :

['11', '12221\n']

. python. lst.

space, : split(' ').

: http://repl.it/R8w

+2

, :

>>> lst = ['11 12221\n']
>>> # Split on spaces explicitly so that the \n is preserved
>>> lst[0].split(" ")
['11', '12221\n']
>>> # Reassign lst to the list returned by lst[0].split(" ")
>>> lst = lst[0].split(" ")
>>> lst
['11', '12221\n']
>>>
+3

:

[part for entry in origlist for part in entry.split(None, 1)]

( ).

+2

std.split:

>>> my_list = ['11 12221\n']     # do not name a variable after a std lib type
>>> my_list = my_list[0].split()
>>> print my_list
['11', '12221']

, str.split . .

+1

Source: https://habr.com/ru/post/1537204/


All Articles