Python 将变量和字符串联接以获取变量
对不起,如果这个问题是关闭的,但这是一些简单的代码Python 将变量和字符串联接以获取变量,python,python-3.x,Python,Python 3.x,对不起,如果这个问题是关闭的,但这是一些简单的代码 quiz_description = 'A quiz to test your knowledge' quiz_type = 'This quiz is about social studies' quiz_length = 'This test is five minutes long' while 0 == 0: user_input = input('What do you want to know about the quiz
quiz_description = 'A quiz to test your knowledge'
quiz_type = 'This quiz is about social studies'
quiz_length = 'This test is five minutes long'
while 0 == 0:
user_input = input('What do you want to know about the quiz? (length|type|description)\n')
print('quiz_' + user_input)
此代码将导致
quick\u length
但是我想加入测验
和用户输入
,即长度
,并生成测验长度
,并显示为该字符串设置的内容,即“此测试有五分钟长”
有什么方法可以做到这一点吗?您应该使用字典来实现这一点:
quiz = {
'description': 'A quiz to test your knowledge',
'type': 'This quiz is about social studies',
'length': 'This test is five minutes long',
}
while 0 == 0:
user_input = input('What do you want to know about the quiz? (length|type|description)\n')
print(quiz.get(user_input, 'Please choose a correct attribute!')
dict.get
将尝试根据第一个参数中的键查找值。如果未找到该键(即,如果用户未输入其中一个建议值),它将在第二个参数中返回该值。这将防止获得键错误