GoatsWearHats
GoatsWearHats

Reputation: 272

Split a string within a list python

I have a list in python, which is from a text document that I split at new line characters. The end of data is indicated with # in the text document. I need to count each of element of the list and then split the strings in the list at tab characters, creating a two dimensional list.

I thought this was fairly simple, however, I'm not getting a result from my code. The strings in the list are not splitting at all, nevermind at \t.

with open('names.txt') as names:
    records = names.read().split('\n')
recordcount = 0
for item in records:
    if item != '#':
        recordcount += 1
        item = item.split('\t')
print (records)
print (recordcount)

Has this got something to do with tab characters being troublesome? Or can I not replace elements of a list in-place? Should I be creating a new list with my split records?

Upvotes: 0

Views: 123

Answers (2)

Manuel Jacob
Manuel Jacob

Reputation: 2004

You can replace list items in-place, but item = item.split('\t') just re-assigns the local variable item. You can easily replace the list item by e.g. records[index] = item. You can get the right index by using the enumerate function.

Your code changed to do what you want:

with open('names.txt') as names:                                            
    records = names.read().split('\n')                                      
recordcount = 0                                                             
for index, item in enumerate(records):                                      
    if item != '#':                                                         
        recordcount += 1                                                    
        item = item.split('\t')                                             
        records[index] = item                                               
print (records)                                                             
print (recordcount)

Upvotes: 1

Alex Hall
Alex Hall

Reputation: 36013

You're just reassigning a local variable. This doesn't affect the contents of the list. Try this:

for i, item in enumerate(records):
    if item != '#':
        recordcount += 1
        records[i] = item.split('\t')

Upvotes: 3

Related Questions