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")
halfer
20.2k20 gold badges111 silver badges208 bronze badges
asked Sep 7, 2017 at 20:38
Mona Coder
6,31218 gold badges71 silver badges140 bronze badges
-
If your question was sufficiently answered, you can accept the most helpful answer.halfer– halfer2019年07月15日 10:48:37 +00:00Commented Jul 15, 2019 at 10:48
3 Answers 3
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.
answered Sep 7, 2017 at 20:43
coldspeed95
407k106 gold badges745 silver badges798 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Alexander
Aren't you mixing methods? Shouldn't you join each component, e.g.
os.path.join(*"C:\\GIS\\Maps\\".split('\\') + ["{}.mxd".format(service)] Surely the `\\` is specific to the operating system, and the point of os.path.join is to join making it OS agnostic.This is how Python's string concatenation works:
sde = "Database Connections\\" + service + ".sde"
mxd = arcpy.mapping.MapDocument("C:\\GIS\\Maps\\" + service + ".mxd")
answered Sep 7, 2017 at 20:40
Djaouad
22.8k4 gold badges37 silver badges57 bronze badges
2 Comments
Mona Coder
Thanks Mr Geek but I am getting error on second line!
Djaouad
@MonaCoder You should escape the
` and remove the r`, check the updated answer.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.
answered Sep 7, 2017 at 20:59
TemporalWolf
8,0121 gold badge33 silver badges54 bronze badges
Comments
lang-py