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"]
To delete a key, value pair in a dictionary, you can use the del method. A disadvantage is that it gives KeyError if you try to delete a nonexistent key. So, instead of the del statement you can use the pop method.
To remove a key from a dictionary in Python, use the pop() method or the “del” keyword. Both methods work the same in that they remove keys from a dictionary. The pop() method accepts a key name as argument whereas “del” accepts a dictionary item after the del keyword.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With