I'm building a tool in python and for that I have a question:

I have a string such as "Denver.dwg Group Layer\Denver.dwg Annotation".

How do I assign to a variable (for later print) only the first part of the string, "Denver.dwg" ?? I need to provide a general solution, as the city name differs from case to case (it might be shorter or longer) and so counting the places until the g of dwg (10 places) won't help.

(I'm writing the python tool for arcgis 9.3.1)

  • 2
    This is a legitimate question, and I think many readers might be interested in the answer, but is it really an appropriate one for this site? It has nothing to do with GIS.
    – whuber
    Dec 30, 2010 at 15:44
  • I thought about it but as I am building a GIS tool I decided to go with it and ask. But if more people think like you, i'd "accept the verdict" and move it or such.
    – jonatr
    Dec 30, 2010 at 15:55
  • 1
    It's not a GIS question, but I think it's a question that other GIS users will have. I would probably lean towards not closing it and providing links to other resources, such as existing stackoverflow.com questions or online tutorials. If it is closed, I think the question will popup again. Dec 30, 2010 at 17:12

3 Answers 3


The code below searches for the first occurence of the ".dwg" string and assigns a new substring (containing characters up to and including that occurence).

text = "Denver.dwg Group Layer\\Denver.dwg Annotation"
ext = ".dwg"

fileNameOnly = text[:text.find(ext) + len(ext)]
print fileNameOnly

This is very basic Python string manipulation. There are loads of quick references which will help you with these most commonly used functions, for example Python Basics, Section 5: Strings.


You should be able to use this string.find method, see my example below.

s = 'Denver.dwg Group Layer/Denver.dwg Annotation"'

# this returns lowest index of first occurence of dwg
# in this case 7
idx = s.find('dwg')
print idx

# take this index and add 3 for 'dwg'
# get desired string
subs = s[:idx+3]
print subs
  • Why would someone post almost identical answer to one already posted?
    – Petr Krebs
    Dec 30, 2010 at 22:46
  • If you look at when the two answers were posted, you'll see they were posted at pretty much the same time- so the second person probably didn't see yours... Dec 31, 2010 at 13:43

str = "Denver.dwg Group Layer\Denver.dwg Annotation"

you can use split

  • c = str.split("\\")

['Denver.dwg Group Layer', 'Denver.dwg Annotation']

the result is a list

d = c[0].split(".") # first term of the list ie 'Denver.dwg Group Layer'

['Denver', 'dwg Group Layer']

d[0] # first term of the list


  • or e = str.split(" ")

['Denver.dwg', 'Group', 'Layer\Denver.dwg', 'Annotation']

  • or f = str.split(" ")[0]



g = f.split(".")

['Denver', 'dwg']



look at Dive Into Python

Not the answer you're looking for? Browse other questions tagged or ask your own question.