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
0

4 Answers 4

2

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
Sign up to request clarification or add additional context in comments.

Comments

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))

Comments

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))

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.