Python中的字符串操作:引号和撇号

时间:2016-10-17 13:07:04

标签: python string operating-system

所以我遇到了python的这个问题:我正在尝试使用python上的os.system创建一个可用于gdal操作的字符串。我的目标是将此操作用于可变数量的输入文件:

os.system('gdal_calc.py -A {0} -B {1} -C {2} --outfile={4} --calc="(1-A)(1-B)(1-C)" '.format(File1, File2, File3, outputfile))

所以这就是我的功能如何:

def Mergefilesforoperation(Inputfiles= None):

    ABC = ["A","B","C","D","E","F","G","H","I","J","K",
    "L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
    partstring = []

    for i in range(len(Inputfiles)-1):
        partstring.append(" -" + ABC[i] +  " '" + Inputfiles[i] + "'")


    wholestring = "".join(partstring)  
    outputfile = 'outputfile.tif'
    operationstring = "gdal_calc.py" + wholestring + " --outfile= {0}".format(outputfile) + ' --calc="(1-A)*(1-B)*(1-C)*(1-D)"'

    return wholestring, operationstring

但是当我返回功能时:

File1 = '/home/File1.tif' File2 = '/home/File2.tif' File3 = '/home/File3.tif'

Mergefilesforoperation(Inputfiles=[File1, File2, File3]) 

它给了我以下输出:

Wholestring = " -A '/home/File1.tif' -B '/home/File2.tif' -C '/home/File3.tif'"

operationstring = 'gdal_calc.py -A \'/home/File1.tif\' -B \'/home/File2.tif\' -C \'/home/File3.tif\' --outfile= outputfile.tif --calc="(1-A)(1-B)(1-C)"')

如何摆脱“operationstring”中字母后面的\符号?

2 个答案:

答案 0 :(得分:0)

做到:

String = ""
for i in range(len(Inputfiles)-1):
    String +=" -" + ABC[i] +  " '" + Inputfiles[i] + "'"

而不是:

 for i in range(len(Inputfiles)-1):
        partstring.append(" -" + ABC[i] +  " '" + Inputfiles[i] + "'")

并使用引号支付报价,我们可以混合报价但是很明显可以遵循一种方法。

operationstring =“gdal_calc.py”+ wholestring +“ - output = {0}”。format(outputfile)+' - calc =“(1-A)(1-B)(1-C)*(1-d)“'

operationstring =“gdal_calc.py”+ wholestring +“ - output = {0}”。format(outputfile)+ --calc = '(1 -A)(1-B)(1-C)*(1-D)'

通过此更改,它可能会起作用。我试过了。

答案 1 :(得分:0)

为了实现这个目的,你必须在单引号内附上双引号,而不是其他方式。

虽然在大多数情况下,两者都应该具有相同的影响,但这是重要的角色之一,因为字符串在Python内部表示。

>>> os.system('dir "C:\\Program Files"')
 Volume in drive C has no label.
 Volume Serial Number is 26BC-5144

 Directory of C:\Program Files

03-10-2016  12:41    <DIR>          .
03-10-2016  12:41    <DIR>          ..
18-07-2016  12:29    <DIR>          Bonjour


>>> os.system("dir 'C:\\Program Files'")
The filename, directory name, or volume label syntax is incorrect.
1

还要注意字符串在内部表示的区别

>>> a
"dir 'C:\\Program Files'"
>>> a.__repr__()
'"dir \'C:\\\\Program Files\'"'
>>> a = 'dir "C:\\Program Files"'
>>> a.__repr__()
'\'dir "C:\\\\Program Files"\''