Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/332.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_String - Fatal编程技术网

Python:字符串替换为括号符号

Python:字符串替换为括号符号,python,string,Python,String,我尝试使用replace函数修改以下字符串: 'hello (world)' 到 但是当我跑的时候 'hello (world)'.replace('(', '\(') 它回来了 'hello \\(world)' 你知道如何达到预期的效果吗 编辑: 问题是,我试图将这些新参数传递给mysql查询,而双反斜杠最终会出现在查询中,使其无效'SELECT datetime,actual,forecast,prior FROM all-data.indicators_ft WHERE count

我尝试使用replace函数修改以下字符串:

'hello (world)'

但是当我跑的时候

'hello (world)'.replace('(', '\(')
它回来了

'hello \\(world)'
你知道如何达到预期的效果吗

编辑:
问题是,我试图将这些新参数传递给mysql查询,而双反斜杠最终会出现在查询中,使其无效
'SELECT datetime,actual,forecast,prior FROM all-data.indicators_ft WHERE country=“United”AND name=“CPI\\(ex Food&Energy\\)%m/m”

我认为您可能会混淆交互式python shell输出与字符串的实际内容:

>>>hello (world)'.replace('(', '\(')
hello \\(world)  
但是


你做得对:

>>> print('hello (world)'.replace('(', '\('))
hello \(world)

获得该输出的原因是,在Python中,反斜杠必须在字符串中转义。因此,Python会自动在字符串中插入一个转义字符。不允许REPL显示字符串的
repr
,而是实际使用
print
,您将看不到双反斜杠
repr
的格式允许使用
eval
重新创建对象,并且由于字符串文字需要转义字符,因此当通过
repr
@leaf使用以下字符串
'CPI(ex Food&Energy)%m/m'显示字符串时,将看到该字符串。替换('(','\\(')
(使用转义反斜杠)还返回相同的错误结果…哦!我不知道。谢谢您的评论。我编辑了您的答案以删除链接并显示代码。以至少四个空格开头的行被格式化为代码。您的答案可以通过解释OP看到错误结果的原因来改进。@deathstroke问题是我试图通过这些nmysql查询的ew参数和双反斜杠最终会出现在查询中,使其无效…
选择datetime、actual、forecast、Previor FROM
所有数据
。indicators\u ft WHERE country=“United States”和name=“CPI\\(ex Food&Energy\\)%m“
问题是,我试图将这些新参数传递给mysql查询,而双反斜杠最终会出现在查询中,使其无效……
”选择datetime、actual、forecast、Previor FROM
所有数据
。indicators\u ft WHERE country=“United”和name=“CPI\\(ex Food&Energy\\\\\\\\%m/m”
>>>print 'hello (world)'.replace('(', '\(')
hello \(world)
>>> print('hello (world)'.replace('(', '\('))
hello \(world)