无法格式化字符串Python

2024-06-02 23:30:39 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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)

Tags: the字符串indatetitlemydefdescription
3条回答
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)

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

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"The poem {title} by {author} was originally published in {original_work} in {publishing_date}."。字符串的前缀为f,然后在字符串内部的花括号之间添加变量

它应该是这样的:

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}."

相关问题 更多 >