0

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
  • 19,824
  • 17
  • 99
  • 186
Mona Coder
  • 6,212
  • 18
  • 66
  • 128

3 Answers3

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.

cs95
  • 379,657
  • 97
  • 704
  • 746
  • 1
    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. – Alexander Sep 07 '17 at 20:53
1

This is how Python's string concatenation works:

sde = "Database Connections\\" + service + ".sde"
mxd = arcpy.mapping.MapDocument("C:\\GIS\\Maps\\" + service + ".mxd")
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55
1

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.

TemporalWolf
  • 7,727
  • 1
  • 30
  • 50