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
20.2k20 gold badges111 silver badges208 bronze badges
asked Sep 7, 2017 at 20:38
1
  • If your question was sufficiently answered, you can accept the most helpful answer. Commented Jul 15, 2019 at 10:48

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

1 Comment

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.
1

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

2 Comments

Thanks Mr Geek but I am getting error on second line!
@MonaCoder You should escape the ` and remove the r`, check the updated answer.
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.

answered Sep 7, 2017 at 20:59

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.