Select to view content in your preferred language

Trying to use rstrip

1868
2
08-20-2013 11:18 AM
MikeOnzay
Frequent Contributor
I want to strip off the last 4 characters of a layer name that is in my mxd. It is the only layer. It is a MrSid file. I want to
export this image to pdf using the layer name without the .sid part. This code exports the map to PDF but it is not stripping off the .sid part. Ex: J-228-01-W-2013.sid.pdf

I used 4 as the number of characters to strip off because I assumed that the dot needs to be removed also.

import arcpy,os

mxd = arcpy.mapping.MapDocument(r"C:\GIS\designsheet.mxd")
df = arcpy.mapping.ListDataFrames(mxd)[0]
df.rotation = 0
lname = arcpy.mapping.ListLayers(mxd)[0].name
outFile = r"C:\GIS\output\\" + lname.rstrip('4') + ".pdf" 
arcpy.mapping.ExportToPDF(mxd, outFile)


- Mike
Tags (2)
0 Kudos
2 Replies
MikeOnzay
Frequent Contributor
I misread the example I was following about how to use rstrip. Instead of using the number of characters I want removed I should use the actual characters! In my example I should have used '.sid' and it works.
0 Kudos
by Anonymous User
Not applicable
The easiest ways to do this are to slice, or split by period.

outFile = r"C:\GIS\output\" + lname[:-4] + ".pdf" 

# OR
 outFile = r"C:\GIS\output\" + lname.split('.')[0] + ".pdf" 


Also, you do not need to have the double backslash when you use the r'' (raw string method)

EDIT:  Sorry, I just realized I had a typo in here.  The colon was supposed to be before the -4 to get everything before the period in the path name.

It would be best to use one of the two methods above.  Sometimes, for some reason, when you try to use strip or rstrip() it will cut off an extra character.  For example:

>>> test = r'C:\Users\Caleb\Desktop\EucDistTools\ascii\polys.shp'
>>> print test.rstrip('.shp')
C:\Users\Caleb\Desktop\EucDistTools\ascii\poly
>>> 


The above was done in the interactive window of Python.  See where it cut off the "s" in polys?  This is why it is better to use split or slicing.  Another method is the os.path.splitext().

>>> import os
>>> print os.path.splitext(test)[0] # 0 index to grab everything before the period
C:\Users\Caleb\Desktop\EucDistTools\ascii\polys
0 Kudos