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")
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.

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")

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.

Comments

Your Answer

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.