You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何实现用户信息录入后按指定格式回显输出

实现方法

代码无法正常运行主要是两个问题:

  • 你定义的info字典键名不统一,部分键末尾带冒号(比如"Name:")、部分不带(比如"Desired Course"),取值时只要键名写的和定义时不完全一致,就会触发KeyError报错。
  • 你写的输出模板本身存在语序错误,you were born in "Birthdate" years old逻辑不通,出生日期字段后多余的years old是写模板时串了后面的年龄字段导致的。

可直接运行的代码

先统一字典键名,去掉所有键末尾多余的冒号降低出错概率,再用f-string做字符串格式化即可:

# 统一键名后的信息存储结构
info = {
    "Name": "x",
    "Birthdate": "x",
    "Gender": "x",
    "Age": "x",
    "Nationality": "x",
    "Desired Course": "x",
    "Motto in life": "x",
    "Dreams in life": "x",
    "Favorite hobby": "x"
}

# 收集用户输入(替换成你原有的输入逻辑即可)
info["Name"] = input("Enter your name: ")
info["Birthdate"] = input("Enter your birthdate: ")
info["Gender"] = input("Enter your gender: ")
info["Age"] = input("Enter your age: ")
info["Nationality"] = input("Enter your nationality: ")
info["Desired Course"] = input("Enter your desired course: ")
info["Motto in life"] = input("Enter your motto in life: ")
info["Dreams in life"] = input("Enter your dreams in life: ")
info["Favorite hobby"] = input("Enter your favorite hobby: ")

# 按指定格式回显,已修正模板语序错误
print(f'So your name is "{info["Name"]}" and you were born in "{info["Birthdate"]}" and you\'re a "{info["Age"]}" year old "{info["Nationality"]}" "{info["Gender"]}" that wants to be a "{info["Desired Course"]}" one day and your motto in life is "{info["Motto in life"]}" and "{info["Dreams in life"]}" and your favorite hobby is "{info["Favorite hobby"]}"')

补充说明

  • 如果你不想修改原有带冒号的字典键,取值时必须严格匹配键名,比如取姓名必须写info["Name:"],漏写末尾冒号就会报错。
  • 字符串内需要输出双引号时,要么外层用单引号包裹整个字符串,要么用转义符\"处理,否则会触发语法错误。
  • 如果需要保留你最初写的带冗余years old的语序,直接修改f-string内的对应文本即可,字段取值逻辑不需要改动。

内容的提问来源于stack exchange,提问作者Joseph Sephy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.10 16:15:46