How can I properly concatenate a variable inside an string in Python?
I am trying to pass service
in "Database Connections\\\\'service'.sde"
and (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
:
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:
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.