python - 使用包含单个反斜杠的字符串的 Python 格式字符串
问题描述
我有一个简单但烦人的问题。我需要使用包含单引号的字符串格式化字符串。所以假设我要格式化这个字符串;
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 有关。对不起,我会打开一个关于它的问题。
解决方案
它需要使用参数化查询:
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",)]
推荐阅读
- angular - “ICellRendererComp”类型上不存在属性“getFrameworkComponentInstance”
- amazon-web-services - aws 实例网络带宽究竟指的是什么?
- in-app-purchase - 在 BillingClient 设置中 .setListener(this) 引用我的调用活动而不是 PurchasesUpdatedListener
- vue.js - 如何在前台运行`nuxt generate`
- javascript - 输入字段添加符号
- javascript - 为什么对 javascript 计数器使用“get”函数?
- vba - Word VBA:调用 FileDialog.Execute 时出现运行时错误“-2147467259 (80004005)”
- sql - Oracle 18c - 左连接条件 USING 子句
- postgresql - 执行交叉表返回 n+ 元组时出错
- python - 如何在多核上的 jupyter notebook 中运行代码?