【问题标题】:Python Format String With a String Which Contains Single Backslash使用包含单个反斜杠的字符串的 Python 格式字符串
【发布时间】:2019-10-23 14:10:37
【问题描述】:

我有一个简单但烦人的问题。我需要使用包含单引号的字符串格式化字符串。所以假设我要格式化这个字符串;

string_to_be_formatted = "Hello, {ANOTHER_STRING}"

那我还有一个字符串;

another_string = r"You\'re genius"

所以最后,我想把字符串设为;

formatted_string = "Hello, You\'re genius"

当我打印 formatted_string 变量时,它按预期打印,但是当我将它用作变量并用它格式化查询时,它使用字符串的表示形式。到目前为止,我已经尝试过;

  • literal_eval 由于单个反斜杠而引发异常
  • 使用 '!s' 选项格式化字符串,结果相同

感谢任何帮助。

编辑:我认为这很可能与 Python clickhouse_driver 有关。很抱歉,我会打开一个关于它的问题。

【问题讨论】:

  • 请显示您用于格式化的确切代码以及生成的字符串。为我工作:a = "Hello, {X}"; b = "foo\'bar"; print(a.format(X=b))
  • 这对我有用string_to_be_formatted.format(ANOTHER_STRING=another_string)
  • 为什么还要在“分隔字符串”中转义单个 '?这不是必需的...

标签: python python-3.x clickhouse


【解决方案1】:

您使用原始字符串来定义数据。这意味着最终的字符串仍将包含反斜杠。如果这是一个错误,解决方法很简单。

>>> template = "Hello, {data}"
>>> value = "You\'re genius"
>>> template.format(data=value)
"Hello, You're genius"

如果您确实有一个带有反斜杠和单引号的字符串,您可以使用literal_eval,但您必须考虑到您必须在末尾和开头添加引号。

>>> template = "Hello, {data}"
>>> value = r"You\'re genius"  # the same as value = "You\\'re genius"
>>> template.format(data=ast.literal_eval(f'"{value}"'))
"Hello, You're genius"

如果你使用的是没有 f-strings 的旧 Python 版本,你可以编写

>>> template.format(data=ast.literal_eval('"' + value + '"'))

【讨论】:

    【解决方案2】:

    需要使用参数化查询:

    from clickhouse_driver import Client
    
    client = Client(host='localhost')
    
    another_string = r"You\'re genius"
    string_to_be_formatted = f'''Hello, {another_string}'''
    
    
    client.execute('INSERT INTO test (str) VALUES (%(str)s)', params={'str': string_to_be_formatted})
    # SELECT *
    # FROM test
    #
    # ┌─str───────────────────┐
    # │ Hello, You\'re genius │
    # └───────────────────────┘
    #
    # 1 rows in set. Elapsed: 0.001 sec.
    
    print(client.execute("SELECT %(str)s", params={'str': string_to_be_formatted}))
    # [("Hello, You\\'re genius",)]
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-30
      • 1970-01-01
      • 1970-01-01
      • 2023-03-20
      相关资源
      最近更新 更多