1

I'm stuck on a problem:

I have a text file called id_numbers.txt that contains this information:

325255, Jan Jansen

334343, Erik Materus

235434, Ali Ahson

645345, Eva Versteeg

534545, Jan de Wilde

345355, Henk de Vries

I need python to split the information at the comma and write a program that will the display the information as follows:

Jan Jansen has cardnumber: 325255

Erik Materus has cardnumber: 334343

Ali Ahson  has cardnumber: 235434

Eva Versteeg has cardnumber: 645345

I've tried to convert to list and split(",") but that ends up adding the next number like this:

['325255', ' Jan Jansen\n334343', ' Erik Materus\n235434', ' Ali Ahson\n645345', ' Eva Versteeg\n534545', ' Jan de Wilde\n345355', ' Henk de Vries']

Help would be appreciated!

1
  • 1
    Can you post your whole example code? Commented Sep 24, 2018 at 16:41

1 Answer 1

4

You can do it this way

with open('id_numbers.txt', 'r') as f:
    for line in f:
        line = line.rstrip() # this removes the \n at the end
        id_num, name = line.split(',')
        name = name.strip() # in case name has trailing spaces in both sides
        print('{0} has cardnumber: {1}'.format(name, id_num))
Sign up to request clarification or add additional context in comments.

10 Comments

lines = f.readlines() is redundant. Just do for line in f.
Keep in mind that name (the second part of the list) will have an extra whitespace at the beginning (the original data has whitespace after a comma).
i will fix that too
do lstrip() on name
Now the first line.rstrip() is redundant as you're removing both the leading and the trailing whitespace with name.strip(). ;)
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.