【问题标题】:How to add quotation on a string for python? [duplicate]如何在python的字符串上添加引号? [复制]
【发布时间】:2021-11-30 18:03:47
【问题描述】:

我想在字符串周围添加引号。

我的代码如下所示:

first_name = "albert"

last_name = "einstein"

message = "A person who never made a mistake never tried anything new."
    
print(f"{first_name.title()} {last_name.title()} once said, {message} ")

输出是:

Albert Einstein once said, A person who never made a mistake never tried anything new.

但我希望输出是:

Albert Einstein once said, "A person who never made a mistake never tried anything new".  

【问题讨论】:

  • 你试过'"' + your_current_string + '"' 吗?

标签: python


【解决方案1】:

只需将代码更改为

first_name = "albert"

last_name = "einstein"

message = '"A person who never made a mistake never tried anything new."'

print(f"{first_name.title()} {last_name.title()} once said, {message} ")

在原始字符串周围使用单引号,以使其他引号 - "" 显示。

您也可以使用斜杠 - \。这充当转义序列。

print(f"{first_name.title()} {last_name.title()} once said, \"{message} \" ")

【讨论】:

    【解决方案2】:

    引号需要显式插入字符串中,类似这样

    # Case-1
    print(f"""{first_name.title()} {last_name.title()} once said, "{message}" """)
    

    结果是

    Albert Einstein once said, "A person who never made a mistake never tried anything new."
    

    由于引号出现在. 之后,因此引号应该进入消息字符串

    # Case -2
    first_name = "albert"
    last_name = "einstein"
    message = '"A person who never made a mistake never tried anything new".'
    
    print(f"{first_name.title()} {last_name.title()} once said, {message} ")
    

    请注意,在第一个示例中,我使用三引号 """ 将字符串括起来,在第二个示例中,它的双引号 " 包含在单个 ' 中。许多这样的组合在 python 中工作。否则像下面这样写消息也可以,但需要转义双引号

    message = "\"A person who never made a mistake never tried anything new\"."
    

    还可以查看这些文档 https://docs.python.org/3/tutorial/introduction.html#strings https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals

    【讨论】:

      【解决方案3】:

      有两种方法可以做到这一点:

      1. 您可以转义双引号,例如: 在双引号后面加上反斜杠会对其进行转义并将其作为字符串的一部分而不是端点
      print(f"{first_name.title()} {last_name.title()} once said, \"{message} \" ")
      
      1. 另一种方式是f用单引号,然后可以不转义使用双引号
      print(f'{first_name.title()} {last_name.title()} once said, "{message}" ')
      

      【讨论】:

      • 正如其他人提到的,您可以在双引号中使用相同的转义/对消息变量使用单引号并将双引号也放在那里
      猜你喜欢
      • 2013-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-24
      • 2023-01-13
      • 2021-06-20
      相关资源
      最近更新 更多