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

Python中如何将用户输入格式化为f-string?如何将输入变量名转实际变量?

如何让用户输入的字符串实现类似f-string的变量替换效果?

你想要的其实是动态字符串插值——让用户输入的包含占位符的字符串,自动替换成已定义的变量值,这完全可以实现,下面给你几种靠谱的方案:

方法1:使用str.format()(你的方案优化版)

你尝试的字典配合format(**variables)的思路非常稳妥,这也是最推荐的安全做法,完善后的代码如下:

# 定义可被替换的变量字典
variables = {'fruit': 'apples', 'colour': 'red'}
# 获取用户输入的带占位符的字符串
message = input('Enter your message: ')
# 用字典键值对替换字符串中的占位符
print(message.format(**variables))

测试时输入I love {fruit} and the colour {colour},就能得到你期望的输出:I love apples and the colour red。这种方式的优势是你能精确控制哪些变量可以被替换,完全避免不必要的安全风险。

方法2:使用string.Template简化占位符写法

如果你想让用户输入的占位符更直观(比如用$fruit代替{fruit}),可以用Python标准库的string.Template:

from string import Template

variables = {'fruit': 'apples', 'colour': 'red'}
message = input('Enter your message: ')
# 创建模板对象
template = Template(message)
# 替换变量并输出
print(template.substitute(variables))

这时候用户输入I love $fruit and the colour $colour,就能得到正确结果。这种写法对用户更友好,同样是安全可控的方案。

方法3:慎用eval()实现完全f-string效果

如果你非要完全模拟f-string的{变量名}写法,也可以用eval(),但一定要警惕安全风险——如果用户输入恶意代码,eval()会直接执行,可能导致危险操作。示例代码:

fruit = 'apples'
colour = 'red'
message = input('Enter your message: ')
# 将用户输入包装成f-string格式后执行
print(eval(f"f'{message}'"))

这种方式能完美复刻f-string的写法,但仅推荐在自己测试、没有不可信用户输入的场景下使用。

总结:普通场景优先选str.format()或string.Template,安全又可控;仅个人测试时,可考虑eval()快速实现需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:17:51