简体   繁体   中英

How can i separate a string that is in a list into 2 parts?

I currently have a list that looks like the following:

list = ['325 153\n', '509 387\n', '419 397\n']

I am wondering how could i access these strings individually so i could use it in a function such as

for (x, y) in list:

where x is the first number of the string and y is the second number (separated by the space)

Is a good way to do this to turn the string into tuples somehow? I have tried using the 'split' function as i believe it is not valid for a list.

>>> a_list = ['325 153\n', '509 387\n', '419 397\n']
>>> [ i.split() for i in a_list ]
[['325', '153'], ['509', '387'], ['419', '397']]

You can iterate one the elements of the list:

for elem in list:
    a, b = elem.split()[0], elem.split()[1]

a and b will be the elements and you can process them just as you wish.

    [tuple(x.split()) for x in list]

这将返回一个元组列表

There is the split() method for string. Before using it you should use strip() to get rid of the training \\n . At the end you can put both into a list comprehension:

for x, y in [item.strip().split(" ", 1) for item in lst]:

Note that I replace list with lst . list is a built-in type and should not be used as variable name.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM