1

I have a txt file, with these contents:

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

And i am putting them into a list, using these lines:

keywords=[]
solutions=[]
for i in file:
    keywords.append((i.split(","))[0])
    solutions.append(((i.split(","))[1]))

but when I print() the solutions, here is what it displays:

['b\n', 'd\n', 'f\n', 'h\n', 'j\n', 'l']

How do I make it, so that the \n-s are removed from the ends of the first 5 elements, bu the last element is left unaltered, using as few lines as possible.

1
  • It doesn't make much sense to call i.split twice; a, b = i.split(","); keywords.append(a); solutions.append(b). Commented Jun 9, 2016 at 18:49

2 Answers 2

2

You can use str.strip() in order to trimming the last whitespace. But as a more pythonic approach you better to use csv module for loading your file content which will accept a delimiter and return an iterable contain tuples of separated items (here, the characters). The use zip() function to get the columns.

import csv
with open(file_name) as f:
    reader_obj = csv.reader(f, delimiter=',') # here passing the delimiter is optional because by default it will consider comma as delimiter.
    first_column, second_column = zip(*reader_obj)
Sign up to request clarification or add additional context in comments.

Comments

0

You need to string.strip() the whitespace/new-line characters from the string after reading it to remove the \n:

keywords=[]
solutions=[]
for i_raw in file:
    i = i_raw.strip() # <-- removes extraneous spaces from start/end of string 
    keywords.append((i.split(","))[0])
    solutions.append(((i.split(","))[1]))

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.