Python: using join on a list , output has brackets

Question:

I feel like its probably a simple solution but I can’t seem to figure it out and my google-fu is failing me.

currently, I’m consuming data from a CSV file, I then read each line and append to a list. I then use join to combine them all but the output is separated by brackets. What am I missing here?

Code:

data_file = csv.reader(open(‘data.csv’,’r’))
ip_addr=[]

for row in data_file:
    ip_addr.append(row)

combine_ips = ‘,’.join(map(str, ip_addr))

Output

[‘1.1.1.1’],[‘1.1.1.2’],[‘1.1.1.3’]

What I need: ( I need it to be a string of course)

1.1.1.1.1,1.1.1.2,1.1.1.3
Asked By: Manik

||

Answers:

No need for the map as ip_addr is a list of strings, not a list of lists

combine_ips = ‘,’.join(ip_addr)
Answered By: wrbp

row evaluates as a list even if it is only a list of 1 in your case, so the first thing you need to do is convert row to a string before appending it to ip_addr. Then, as pointed out by @wrbp you only need to join the (now) string contents of ip_addr:

data_file = csv.reader(open("data.csv","r"))
ip_addr=[]

for row in data_file:
    ip_addr.append("".join(row))

combine_ips = ",".join(ip_addr)
Answered By: rhurwitz
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.