繁体   English   中英

替换混合引用字符串 python 中的反斜杠

[英]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是我从某处获取的变量,因此我需要将其作为字符串放在单引号内,因为它是命令行工具的参数。

我尝试使用replaceregex没有任何成功。

我正在构建一个字符串作为参数传递给带有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.

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