Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python格式字符串,其中包含一个反斜杠_Python_Python 3.x_Clickhouse - Fatal编程技术网

Python格式字符串,其中包含一个反斜杠

Python格式字符串,其中包含一个反斜杠,python,python-3.x,clickhouse,Python,Python 3.x,Clickhouse,我有一个简单但烦人的问题。我需要用包含单引号的字符串格式化字符串。假设我要格式化这个字符串 string_to_be_formatted = "Hello, {ANOTHER_STRING}" 然后我有另一根绳子 another_string = r"You\'re genius" 所以在最后,我想把字符串作为 formatted_string = "Hello, You\'re genius" 当我打印格式化的_字符串变量时,它会按预期打印,但是当我将其用作变量并使用它格式化查询时,它会

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

string_to_be_formatted = "Hello, {ANOTHER_STRING}"
然后我有另一根绳子

another_string = r"You\'re genius"
所以在最后,我想把字符串作为

formatted_string = "Hello, You\'re genius"
当我打印格式化的_字符串变量时,它会按预期打印,但是当我将其用作变量并使用它格式化查询时,它会使用字符串的表示形式。到目前为止我已经试过了

由于单个反斜杠而引发异常的literal_eval 将字符串格式化为“!s’选项,同样的结果 感谢您的帮助


编辑:我认为这很可能与Python clickhouse\u驱动程序有关。很抱歉,我将就此打开一个问题。

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

>>> template = "Hello, {data}"
>>> value = "You\'re genius"
>>> template.format(data=value)
"Hello, You're genius"
如果你真的有一个带反斜杠和单引号的字符串,你可以使用,但你必须考虑到,你必须在末尾和开头加引号

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

它需要使用参数化查询:

从clickhouse\u驱动程序导入客户端 client=Clienthost='localhost' 你真是天才 string_to_be_formatted=f'Hello,{other_string}' 执行'INSERT INTO test str VALUES%strs',参数={'str':字符串\u to \u be \u formatted} 挑选* 从测试 ┌─str───────────────────┐ │ 你好,你是天才│ └───────────────────────┘ 一组1行。经过时间:0.001秒。 printclient.executeSELECT%strs,params={'str':字符串要格式化} [你好,你是天才,\\\]
请显示用于格式化的确切代码以及生成的字符串。为我工作:a=Hello,{X};b=foo'bar;printa.formatX=b这对我来说很有用,字符串要格式化。formatANOTHER\u string=another\u string为什么要在分隔字符串中转义单个?这是不需要的。。。