O.rka
O.rka

Reputation: 30687

Partitioning elements in list by \t . Python

my_list = ['1\tMelkor\tMorgoth\tSauronAtDolGoldul','2\tThingols\tHeirIsDior\tSilmaril','3\tArkenstone\tIsProbablyA\tSilmaril']

I'm trying to split this list into sublists separated by \t

output = [['1','Melkor','Morgoth','SauronAtDolGoldul'],['2','Thigols','HeirIsDior','Silmaril'],['3','Arkenstone','IsProbablyA','Silmaril']]

I was thinking something on the lines of

output = []
for k_string in my_list:
    temp = []
    for i in k_string:
        temp_s = ''
        if i != '\':
            temp_s = temp_s + i
        elif i == '\':
            break
        temp.append(temp_s)

it gets messed up with the t . . i'm not sure how else I would go about doing it. I've seen people use .join for similar things but I don't really understand how to use .join

Upvotes: 0

Views: 848

Answers (2)

jamylak
jamylak

Reputation: 133564

>>> import csv
>>> my_list = ['1\tMelkor\tMorgoth\tSauronAtDolGoldul','2\tThingols\tHeirIsDior\tSilmaril','3\tArkenstone\tIsProbablyA\tSilmaril']
>>> list(csv.reader(my_list, delimiter='\t'))
[['1', 'Melkor', 'Morgoth', 'SauronAtDolGoldul'], ['2', 'Thingols', 'HeirIsDior', 'Silmaril'], ['3', 'Arkenstone', 'IsProbablyA', 'Silmaril']]

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1122092

You want to use str.split(); a list comprehension lets you apply this to all elements in one line:

output = [sub.split('\t') for sub in my_list]

There is no literal \ in the string; the \t is an escape code that signifies the tab character.

Demo:

>>> my_list = ['1\tMelkor\tMorgoth\tSauronAtDolGoldul','2\tThingols\tHeirIsDior\tSilmaril','3\tArkenstone\tIsProbablyA\tSilmaril']
>>> [sub.split('\t') for sub in my_list]
[['1', 'Melkor', 'Morgoth', 'SauronAtDolGoldul'], ['2', 'Thingols', 'HeirIsDior', 'Silmaril'], ['3', 'Arkenstone', 'IsProbablyA', 'Silmaril']]

Upvotes: 4

Related Questions