首页 > 解决方案 > 使用包含单个反斜杠的字符串的 Python 格式字符串

问题描述

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

string_to_be_formatted = "Hello, {ANOTHER_STRING}"

然后我有另一个字符串;

another_string = r"You\'re genius"

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

formatted_string = "Hello, You\'re genius"

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

任何帮助表示赞赏。

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

标签: pythonpython-3.xclickhouse

解决方案


它需要使用参数化查询:

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",)]


推荐阅读