结束 ='' 不工作 (Python)

end='' not working (Python)

我试图将程序的输出全部放在一行上,但当我打印 "end=''" 时,它似乎无法正常工作。有任何想法吗?

这是我的代码:

import random

thesaurus = {}
with open('thesaurus.txt') as input_file:
    for line in input_file:
        synonyms = line.split(',')
        thesaurus[synonyms[0]] = synonyms[1:]

print ("Total words in thesaurus: ", len(thesaurus))

# input
phrase = input("Enter a phrase: ")

# turn input into list
part1 = phrase.split()
part2 = list(part1)


newlist = []
for x in part2:
    s = random.choice(thesaurus[x]) if x in thesaurus else x
    s = random.choice(thesaurus[x]).upper() if x in thesaurus else x
    newlist.append(s)

newphrase = ' '.join(newlist)

print(newphrase, end=' ')

现在,出于某种原因,我的程序正在打印:

i LOVE FREEDOM
 SUFFICIENCY apples

输入"i like to eat apples"

预期输出为:

 i LOVE FREEDOM SUFFICIENCY apples

感谢任何帮助!!

end='' 完全不是问题。从文件中读取的行仍然有换行符。拆分行时,最终条目将有一个换行符,如本例所示:

>>> 'foo,bar,baz\n'.split(',')
['foo', 'bar', 'baz\n']

您的问题是您替换了 "FREEDOM\n" 而不仅仅是 "FREEDOM"。使用前先去掉线:

thesaurus = {}
with open('thesaurus.txt') as input_file:
    for line in input_file:
        synonyms = line.strip().split(',')
        thesaurus[synonyms[0]] = synonyms[1:]