6

I'm looking for a Python or VB statement to remove the last part of a string, starting where the 1st non Numeric character appears, using the Field Calculator in ArcMap 10. Here's an example of what I'm looking for:

enter image description here

Is it possible?

closed as off-topic by Hornbydd, Simbamangu, user30184, AndreJ, Erica Oct 17 '14 at 11:22

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Questions about general computing hardware and software are off-topic here, but can be asked on Super User." – Hornbydd, Simbamangu, user30184, AndreJ
If this question can be reworded to fit the rules in the help center, please edit the question.

  • Its not something I have much experience with but this sounds like a regular expression type problem. Have a look at this website. – Hornbydd Oct 16 '14 at 22:35
  • 1
    Despite being used in the Python Parser of the Field Calculator of ArcGIS for Desktop, this looks like a pure Python question that would be better researched/asked at StackOverflow.com. – PolyGeo Oct 16 '14 at 23:01
6

Here's a go at it. Use Python as the parser and check show Codeblock.

Enter this in the top Pre-Logic Script Code box:

def getints(field):

    integers = []
    for char in field:
        try:        
            value = int(char)
            integers.append(str(value))
        except ValueError:
            break

    return "".join(integers)

And put this in the bottom box:

getints(!YOURFIELD!)
  • @AntonioH Awesome! – ianbroad Oct 16 '14 at 23:51
  • How should I edit this python code if I wanted to "extract" all the consecutive numbers? For example: Original String: "ADD. 420-" Final String: "420". Thanks! – AntonioH Dec 2 '15 at 2:10
  • @AntonioH You'll want to use the 'isdigit() ' method. I'm on my phone, but I'll try to show an example tomorrow. – ianbroad Dec 4 '15 at 6:20
4

Here is a field calculator method that incorporates itertools.takewhile. While ian's solution writes the new values to a text field, this is suited for writing to a numeric field.

import itertools

def convert(x):
  try:
    return int("".join(itertools.takewhile(str.isdigit, str(x))))
  except:
    pass

convert(!OriginalString!)

enter image description here

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