Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python remove brackets and String quotation marks from array

myArray = []
textFile = open("file.txt")
lines = textFile.readlines()
for line in lines:
    myArray.append(line.split(" "))
print (myArray)

This code outputs

[['a\n'], ['b\n'], ['c\n'], ['d']]

What would I need to do to make it output

a, b, c, d
like image 824
Guybrush Threepwood Avatar asked Sep 16 '25 20:09

Guybrush Threepwood


1 Answers

You're adding a list to your result (split returns a list). Moreover, specifying "space" for split character isn't the best choice, because it doesn't remove linefeed, carriage return, double spaces which create an empty element.

You could do this using a list comprehension, splitting the items without argument (so the \n naturally goes away)

with open("file.txt") as lines:
    myArray = [x for line in lines for x in line.split()]

(note the with block so file is closed as soon as exited, and the double loop to "flatten" the list of lists into a single list: can handle more than 1 element in a line)

then, either you print the representation of the array

print (myArray)

to get:

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

or you generate a joined string using comma+space

print(", ".join(myArray))

result:

 a, b, c, d
like image 182
Jean-François Fabre Avatar answered Sep 19 '25 09:09

Jean-François Fabre