简体   繁体   English

在Python中串联字符串

[英]Concatenating strings in Python

How can I properly concatenate a variable inside an string in Python? 如何在Python中的字符串内正确连接变量?

I am trying to pass service in "Database Connections\\\\'service'.sde" and (r"C:\\GIS\\Maps\\'.+service+.'.mxd") 我试图通过service"Database Connections\\\\'service'.sde"(r"C:\\GIS\\Maps\\'.+service+.'.mxd")

service ="Electric"
sde = "Database Connections\\'service'.sde"
mxd = arcpy.mapping.MapDocument(r"C:\GIS\Maps\'.+service+.'.mxd")

so the output looks like 所以输出看起来像

sde = "Database Connections\\Electric.sde"
mxd = arcpy.mapping.MapDocument(r"C:\GIS\Maps\Electric.mxd")

I think a better way to do this is using os.path.join : 我认为一种更好的方法是使用os.path.join

import os
mxd = arcpy.mapping.MapDocument(os.path.join(*"C:\\GIS\\Maps\\".split('\\') 
                                                    + ["{}.mxd".format(service)]))

Also, note that your back-slashes need to be escaped. 另外,请注意,您的反斜杠需要转义。

This is how Python's string concatenation works: 这是Python的字符串连接的工作方式:

sde = "Database Connections\\" + service + ".sde"
mxd = arcpy.mapping.MapDocument("C:\\GIS\\Maps\\" + service + ".mxd")

An alternative which bypasses the issue of raw strings can't end with a single backslash : 绕过原始字符串问题的替代方法不能以单个反斜杠结束

r'C:\GIS\Maps\%s.mxd' % service

and

r'C:\GIS\Maps\{}.mxd'.format(service)

both work fine, dodging the issue with the string ending in a backslash. 两者都可以正常工作,可以避免出现以反斜杠结尾的字符串的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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