繁体   English   中英

Python 使用包含单个反斜杠的字符串格式化字符串

[英]Python Format String With a String Which Contains Single Backslash

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

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 有关。 对不起,我会打开一个关于它的问题。

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

>>> 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 + '"'))

如果打印出Hello, your\re a genius就是你想要的,是不是很简单:

str1 = "Hello"
str2 = "you\\'re a genius"

formated_str = f"{str1}, {str2}"

打印: Hello, you\'re a genius

双反斜杠会给你一个字符串上的实际反斜杠。

它需要使用参数化查询:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM