簡體   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