4
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

4 Answers4

3

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
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
0

You could do the following:

myArray = [[v.strip() for v in x] for x in myArray]

This will remove all the formatting characters.

If you do not want each character to be in its own array, you could then do:

myArray = [v[0] for v in myArray]

To print, then 'print(', '.join(myArray))

Deem
  • 7,007
  • 2
  • 19
  • 23
0

It seems you should be using strip() (trim whitespace) rather than split() (which generates a list of chunks of string.

myArray.append(line.strip())

Then 'print(myArray)' will generate:

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

To print 'a, b, c, d' you can use join():

print(', '.join(myArray))
T Semple
  • 99
  • 1
  • 4
0

You can try something like:

import re
arr = [['a\n'], ['b\n'], ['c\n'], ['d']]
arr = ( ", ".join( repr(e) for e in arr ))
arr = arr.replace('\\n', '')
new = re.sub(r'[^a-zA-Z0-9,]+', '', arr)
print(new)

Result:

a,b,c,d
RPT
  • 728
  • 1
  • 10
  • 29