包含单个反斜杠的字符串的python格式字符串

vfh0ocws  于 2021-07-15  发布在  ClickHouse
关注(0)|答案(2)|浏览(352)

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

string_to_be_formatted = "Hello, {ANOTHER_STRING}"

然后我有另一根弦;

another_string = r"You\'re genius"

所以在最后,我想有字符串作为;

formatted_string = "Hello, You\'re genius"

当我打印格式化的字符串变量时,它会按预期打印,但是当我将它用作变量并用它格式化查询时,它会使用字符串的表示形式。到目前为止我已经试过了;
由于单个反斜杠而引发异常的literal\u eval
用''格式化字符串!s的选择,同样的结果
感谢您的帮助。
编辑:我认为这很可能与python clickhouse驱动程序有关。很抱歉,我会就此提出一个问题。

kgsdhlau

kgsdhlau1#

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

>>> 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字符串的旧python版本,那么您可以编写

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

nnt7mjpx2#

它需要使用参数化查询:

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

相关问题