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!

zwer
  • 24,943
  • 3
  • 48
  • 66
Joshua
  • 19
  • 5

1 Answers1

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))
Atul Shanbhag
  • 636
  • 5
  • 13
  • 2
    `lines = f.readlines()` is redundant. Just do `for line in f`. – FHTMitchell Sep 24 '18 at 16:41
  • 1
    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). – zwer Sep 24 '18 at 16:44
  • i will fix that too – Atul Shanbhag Sep 24 '18 at 16:44
  • do lstrip() on name – Tanmay jain Sep 24 '18 at 16:44
  • Now the first `line.rstrip()` is redundant as you're removing both the leading and the trailing whitespace with `name.strip()`. ;) – zwer Sep 24 '18 at 16:46
  • Is this python 3.0? It works perfectly but I was just curious as it doesn't look like python code I recognize! Thanks anyway! – Joshua Sep 24 '18 at 16:47
  • `f'{name} has card number: {id_num}'` for python3.6+ – rafaelc Sep 24 '18 at 16:48
  • @Joshua - Can be both. In Python 3.x `print` is a function, not a statement but having some extra (redundant) brackets around `print` arguments on Python 2.x is perfectly OK. [`str.format()`](https://docs.python.org/3/library/stdtypes.html#str.format) exists in Python since 2.6 and [context managers](https://docs.python.org/3/reference/datamodel.html#context-managers) (`with...`) exist since 2.5. – zwer Sep 24 '18 at 16:51
  • By the way Atul, no need for so many lines. can just do `id_num, name = line.strip().split(',')` and `'{0} has cardnumber: {1}'.format(name.strip(), id_num)` – rafaelc Sep 24 '18 at 17:01
  • Yeah I know that, I tried to keep the code as readable as possible – Atul Shanbhag Sep 24 '18 at 17:11