打印字典变量

时间:2018-08-27 05:32:44

标签: python string python-3.x dictionary replace

BRANDS = {
'Velcro': 'hook and loop fastener',
'Kleenex': 'tissues',
'Hoover': 'vacuum',
'Bandaid': 'sticking plaster',
'Thermos': 'vacuum flask',
'Dumpster': 'garbage bin',
'Rollerblade': 'inline skate',
'Aspirin': 'acetylsalicylic acid'
}
sentence = input (Sentence: )

我希望它打印出这样的内容:

Sentence: I bought some Velcro shoes.
I bought some hook and loop fastener shoes.

1 个答案:

答案 0 :(得分:0)

使用以下方法同意@Burhan的想法:

sentence = input('Sentence: ')
print(' '.join(BRANDS.get(i,i) for i in sentence.split()))

也可以使用for循环:

sentence = input('Sentence: ')
for i in sentence.split():
   sentence=sentence.replace(i,BRANDS.get(i,i))
print(sentence)