简体   繁体   中英

Dictionary is giving \n error, how do I get rid of the \n?

I have some code that randomly generates a word from the .txt file. I want this word to also print it's matching definition but it's not working

This is what I currently have

keywords = {'carrot': 'Green Vegetable.',
            'apple': 'Red or Green fruit.',
            'orange': 'Orange fruit.'}

print ("Here is your keyword")
import random
with open('keywords.txt') as f:
     a = random.choice(list(f))
     print (a)

print (keywords[a])

It successfully generates the random keyword but does not show the keyword's definition. This is the error that shows

, line 11, in <module>
    print (keywords[a])
KeyError: 'apple\n' 

The error, I believe, is suggesting that my keywords.txt file claims that the keyword includes \\n but It most certainly does not, I have not typed \\n anywhere in my code or my .txt file.

Well this is probably because of whitespace characters, like \\n or just your regular old space. You can remove them by random.choice(list(f)).strip() .

Lines from file contain new line ( \\n ) characters.

You should strip them.

>>> 'apple\n'.rstrip()
'apple'

>>> 'apple\n'.rstrip('\r\n') # if you want strip only trailing CR and NL.
'apple'

with open('keywords.txt') as f:
    a = random.choice([line.rstrip() for line in f])
    print (a)

您可以使用:

a = a.replace('\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