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

如何在Python字符串中插入变量?新手开发Madlibs游戏遇变量调用问题

错误原因

你当前的%字符串格式化用法不符合Python语法要求,具体错误如下:

  • 缺少占位符:使用%格式化时,需要先在字符串中对应位置填写占位符%s(表示插入字符串类型内容),不能直接把%变量名插在字符串片段中间
  • 格式结构错误:%需要放在完整的待格式化字符串尾部,后面跟要替换的变量/变量元组,不能拆分到多段字符串中间使用
  • 额外语法问题:你当前写的print语句末尾缺少闭合的右括号),运行也会报错

修正方案

方案1:按你参考的%格式化写法调整

把你报错的print行替换为以下代码即可:

print("One Day, there was a %s woman. This woman, was on a walk one day, when she saw a %s. She looked at the %s and thought to herself, %s looks like a %s." % (adjective1, noun1, noun1, noun1, noun2))

方案2:更适合新手的f-string写法(Python 3.6+支持)

这种写法不需要记占位符顺序,直接把变量嵌在字符串里,可读性更高,更不容易出错:

print(f"One Day, there was a {adjective1} woman. This woman, was on a walk one day, when she saw a {noun1}. She looked at the {noun1} and thought to herself, {noun1} looks like a {noun2}.")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 13:15:03