Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/278.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 2.7_Python 3.x - Fatal编程技术网

在python中使用字符串时出错

在python中使用字符串时出错,python,python-2.7,python-3.x,Python,Python 2.7,Python 3.x,我正在分配一个变量,如下所示: cmd="sed -i 's/id="556"/id="33442233"\n pss="120"/g' a.xml" 但是当我试图打印cmd时,我得到了一个语法错误,似乎是 由于有多个“和”…如何解决此问题?使用\转义引号 cmd="sed -i 's/id=\"556\"/id=\"33442233\"\n pss=\"120\"/g' a.xml" 使用\转义引号 cmd="sed -i 's/id=\"556\"/id=\"33442233\"\

我正在分配一个变量,如下所示:

cmd="sed -i 's/id="556"/id="33442233"\n    pss="120"/g' a.xml"
但是当我试图打印cmd时,我得到了一个语法错误,似乎是
由于有多个
…如何解决此问题?

使用
\
转义引号

cmd="sed -i 's/id=\"556\"/id=\"33442233\"\n pss=\"120\"/g' a.xml"

使用
\
转义引号

cmd="sed -i 's/id=\"556\"/id=\"33442233\"\n pss=\"120\"/g' a.xml"
使用三重引号:

cmd = '''sed -i 's/id="556"/id="33442233"\n pss="120"/g' a.xml'''
顺便说一句,我在那里看到了
\n
-如果您想将其保留为反斜杠-n,而不是将其转换为单个换行符,您甚至可以使用以下方法:

cmd = r'''sed -i 's/id="556"/id="33442233"\n pss="120"/g' a.xml'''
使用三重引号:

cmd = '''sed -i 's/id="556"/id="33442233"\n pss="120"/g' a.xml'''
顺便说一句,我在那里看到了
\n
-如果您想将其保留为反斜杠-n,而不是将其转换为单个换行符,您甚至可以使用以下方法:

cmd = r'''sed -i 's/id="556"/id="33442233"\n pss="120"/g' a.xml'''
为我工作:

Python 2.7.9 (v2.7.9:648dcafa7e5f, Dec 10 2014, 10:10:46) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> cmd="sed -i \'s\/id=\"556\"\/id=\"33442233\"\n    pss=\"120\"\/g\' a.xml"
>>> print cmd
sed -i 's\/id="556"\/id="33442233"
    pss="120"\/g' a.xml
为我工作:

Python 2.7.9 (v2.7.9:648dcafa7e5f, Dec 10 2014, 10:10:46) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> cmd="sed -i \'s\/id=\"556\"\/id=\"33442233\"\n    pss=\"120\"\/g\' a.xml"
>>> print cmd
sed -i 's\/id="556"\/id="33442233"
    pss="120"\/g' a.xml

要转义引号,请在字符前加反斜杠
\
。例如:

“\'hello\”他说。
“\'debye\”她说

要转义引号,请在字符前面加一个反斜杠。例如:
“\'hello\'他说。”
“\'再见\'她说”