[英]Replace backslash in mixed quoted string python
我正在為一個非常簡單的任務而苦苦掙扎。 我正在編寫如下字符串:
myvalue = '001'
s = '''-where "myfield='{}'" '''.format(myvalue)
print(s)
'''-where "myfield=\'001\'" '''
但我需要的是
expected_string = '''-where "myfield='001'" '''
print(expected_string)
'-where "myfield='001'" '
myvalue
是我從某處獲取的變量,因此我需要將其作為字符串放在單引號內,因為它是命令行工具的參數。
我嘗試使用replace
和regex
沒有任何成功。
我正在構建一個字符串作為參數傳遞給帶有where參數的ogr2ogr
,所以基本上是一個 SQL 語句。 然后將該字符串傳遞給一個包裝器,該包裝器檢查查詢是否正確,並使用\'
它抱怨。
您可以使用雙引號代替撇號。
myvalue = '001'
s = """-where "myfield='{}'" """.format(myvalue)
print(s)
[OUT]:-where "myfield='001'"
並提醒 python 3.7 附帶的 f-string 功能,您可以消除格式部分。
myvalue = '001'
s = f"""-where "myfield='{myvalue}'" """
print(s)
[OUT]:-where "myfield='001'"
使用替換() function
myvalue = '\ 001\ '
s = """-where "myfield='{}'" """.format(myvalue)
s = s.replace("\\","")
print(s)
-where "myfield='001'"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.