python - 将字典传递给python中的字符串

标签 python string dictionary

我正在尝试使用键值对格式化字符串,其中字符串中的变量修饰符由键的名称引用。

我该怎么做?这是我的代码:

given_string2 = "I'm %(name)s. My real name is %(nickname)s, but my friends call me %(name)s."
def sub_m(name, nickname):
    return given_string2 %{name:nickname}
print sub_m("Mike","Goose")

最佳答案

你的问题在这里:given_string2 % {name: nickname}

这个有效:

>>> "I'm %(name)s. My real name is %(nickname)s, but my friends call me %(name)s." % {'name': "Mike", 'nickname': "Goose"}
"I'm Mike. My real name is Goose, but my friends call me Mike."

关于python - 将字典传递给python中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20917289/

相关文章:

python - 使用 setdefault 重构 Python Dicts 列表

python - GridSearchCV 将为此运行多少种组合?

Python 零除错误

python - 页码python-docx

python - 在 Python 列表中高效搜索部分字符串

c# - 按键获取字典值

c++ - 使用具有由字符串 C++ 定义的 map 名称的 map

python - 在 ubuntu 14.04 上安装 tkinter

r - 两个字符串的最佳相似性距离度量

c++ - "expected unqualified-id before ' void '"& "string in class does not name a type"错误