无法格式化字符串-Python

无法格式化字符串-Python,python,format,Python,Format,我无法格式化这个字符串,为什么会这样 def poem_description(publishing_date, author, title, original_work): poem_desc = "The poem {title} by {author} was originally published in {original_work} in {publishing_date}.".format(publishing_date, author, title, or

我无法格式化这个字符串,为什么会这样

def poem_description(publishing_date, author, title, original_work):
  poem_desc = "The poem {title} by {author} was originally published in {original_work} in {publishing_date}.".format(publishing_date, author, title, original_work)
  return poem_desc

my_beard_description = poem_description("1897", "Tauqeer", "Venice", "1992")

print(my_beard_description)

它应该是这样的:

poem_desc = "The poem {} by {} was originally published in {} `in {}.".format(publishing_date, author, title, original_work)`
或者像这样:

poem_desc = f"The poem {title} by {author} was originally published in {original_work} in {publishing_date}."

花括号应为空
{}
。在花括号之间键入了变量。只要去掉它们,你就可以走了

def poem_description(publishing_date, author, title, original_work):
  poem_desc = "The poem {} by {} was originally published in {} in {}.".format(title, author, original_work, publishing_date)
  return poem_desc

my_beard_description = poem_description("1897", "Tauqeer", "Venice", "1992")

print(my_beard_description)

此外,您还可以使用格式化字符串
poem_desc=f“{author}的诗{title}最初是在{publishing_date}的{original_work}中发表的。”
字符串的前缀是
f
,然后在字符串内部的花括号之间添加变量。

如果要保持花括号语法,必须使用
.format\u map
而不是
.format
或使用字典解包。目前,它需要一个包含键
title
author
和所有其他键的词典都不存在

def poem_description(publishing_date, author, title, original_work):
    poem_desc = "The poem {title} by {author} was originally published in {original_work} in {publishing_date}.".format(publishing_date=publishing_date, author=author, title=title, original_work=original_work)
    return poem_desc


my_beard_description = poem_description("1897", "Tauqeer", "Venice", "1992")

# Print the result
print(my_beard_description)
my_dict = {"title" : title, "author" : author} 
poem_desc = "The poem {title} by {author}".format_map(my_dict)
# or simply
poem_desc = "The poem {title} by {author}".format_map(**my_dict)

你能说清楚吗?错误是什么?预期的输出是什么?您所说的“您无法”是什么意思?以下消息显示“回溯(最近一次调用):文件“C:/Users/Tauqeer Shoaib/PycharmProjects/HelloWorld/main.py”,第5行,在my_beard_description=poem_description(“1897”,“Tauqeer”,“Venice”,“1992”)文件中”C:/Users/Tauqeer Shoaib/PycharmProjects/HelloWorld/main.py”,第2行,在poem_description poem_desc=“The poem{title}by{author}最初是在{publishing_date}的{original_work}中发表的
format
是passé。当然这个替代方法可以工作,但它不能回答为什么会这样的问题。当我在参数和字符串中添加关键字时,它可以工作fine@t92嗯,当使用字符串格式时,不应该在其中添加参数。当使用f字符串时,它需要参数。不过String.format是基于参数顺序的。我不应该在其中添加参数?@t92使用String格式时不应该在其中添加参数。使用f-string时需要参数。因此,只有在参数和字符串中添加关键字时,我才应该在花括号中添加变量?如果使用格式化字符串,字符串前缀为
f
,则只应该在花括号中添加变量
string=f“a-{a}的值”
@t92只需使用f-string,例如
f'thepoem{title}…'
。删除
.format
(Python 3.6+)。