打印词典变量

2024-06-14 08:53:31 发布

您现在位置:Python中文网/ 问答频道 /正文

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.

Tags: andloopsomehooksentencehoovervacuumkleenex
1条回答
网友
1楼 · 发布于 2024-06-14 08:53:31

同意@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)

相关问题 更多 >