简体   繁体   中英

Python print item from dictionary returns newline symbol only

Item: '1;Paul;Crowe;28;male;2\\n'

Code:

f = open('data.txt', 'r+').readlines()

l = len(f)

data = {}
friends = {}

for i in range(0,l):
    person = f[i].split(';')
    friend = f[i][-1]
    data.update({person[0]:person[1:]})
    friends.update({osoba[0]:friend})

print friends

And the output of print:

{'11': '\n', '10': '\n', '13': '\n', '12': '\n', '15': '\n', '14': '\n', '17': '\n', '16': '\n', '19': '\n', '18': '\n', '20': '\n', '1': '\n', '3': '\n', '2': '\n', '5': '\n', '4': '\n', '7': '\n', '6': '\n', '9': '\n', '8': '\n'}

I don't understand why does it not return the '2\\n' string instead. What seems to be the problem?

It returns '\\n' because in the line friend = f[i][-1] you are retrieving the last character of the ith row in the file. That last character is '\\n' . I think what you want to do is:

friend = f[i].split(';')[-1] # This will return 2\n

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM