qorhvk
qorhvk

Reputation: 51

How do we remove ' ' from the list?

So I am trying to read line by line from the text file using python And I got list of lists. And I have to use the elements of the list to create dictionary. So what I did was

list1 = []
for line in file:
   lines = line.strip().split()
   list1.append(lines)
print(list1)

And what I got when I ran it is the list of lists but something different than what I wanted to get, I got something like this,

['a,b,c,d,e,f']

What I wanted to get was something like this,

[a,b,c,d,e,f]

So how do we get rid of that ' ' inside the list? I tried to use remove method, but it did not work.

Upvotes: 4

Views: 157

Answers (3)

Madhur Jain
Madhur Jain

Reputation: 101

Just change the delimeter from '' to ','

list1 = []
for line in file:
   lines = line.strip().split(,)
   list1.append(lines)
print(list1)

you are good to go

Upvotes: 0

Shreyas Pande
Shreyas Pande

Reputation: 149

you just need to change the separator in the strip from the default white space to ",". i.e you just need to add the separator argument in the strip function .

list1 = []
for line in file:
   lines = line.strip().split(',')
   list1.append(lines)
print(list1)

so if text is:

a,b,c,d,e,f

the strip function would take the separator as "," and create a list for it.

hence the output would be:

['a','b','c','d','e','f']

therefore finally you just need to change the separator argument of line.strip() from white spaces to comma separated list and you are done with it .

Upvotes: 2

cglacet
cglacet

Reputation: 10962

What you have here is a list with a single element. It contains a single string which is 'a,b,c,d,e,f'.

We can double-check:

data = ['a,b,c,d,e,f']
print(len(data)) # prints 1
print(data[0])   # prints 'a,b,c,d,e,f'

What you want is to split this string into a list:

row = data[0].split(',')

Now row contains what you expected data to be, which is ['a', 'b', 'c', 'd', 'e', 'f'].

In a real case you would probably fix this while reading the file, the code might look like this:

list1 = []

with open('test.csv') as test_file:
    for line in test_file:
        list1.append(line.strip().split(','))

print(list1)

Now you would then have a list per line in your input file:

[
    ['a', 'b', 'c', 'd', 'e', 'f'], 
    ['g', 'h', 'i', 'j', 'k', 'l'],
]

Upvotes: 0

Related Questions