D. K.
D. K.

Reputation: 137

removing \n in dictionary

I've got a problem with removing \n in my program here is the code

with open(filename) as f:
    for line in f.readlines():
        parent, child = line.split(",")
            parent.strip()
            child.strip()
            children[child].append(parent)

tried using .rstrip and other variants but it does nothing for my, this is the result i get

{'Patricia\n': ['Mary'], 'Lisa\n': ['Mary']} 

the problem is when i call children["Patricia"] i get [], because it recognizes only children["Patricia\n"]

Upvotes: 6

Views: 1338

Answers (3)

Mayank Porwal
Mayank Porwal

Reputation: 34086

Please use strip before split:

parent, child = line.rstrip("\n").split(",")

Issue was: parent.strip() needs to be re-assigned to a string as strings are immutable.

Upvotes: 4

Dušan Maďar
Dušan Maďar

Reputation: 9909

Actually, you were quite close. Strings are immutable and hence calling strip() will return a new string while leaving the original one intact.

So replacing

parent.strip()
child.strip()

with

parent = parent.strip()
child = child.strip()

would do the trick.

Upvotes: 9

boonwj
boonwj

Reputation: 356

Calling strip() on its own does not change the original value. You will either need to assign to a variable first or use it within your dictionary creation.

Do see if the following snippet solves you problem

with open(filename) as f:
    for line in f.readlines():
        parent, child = line.split(",")
            children[child.strip()].append(parent.strip())

Upvotes: 3

Related Questions