1

I'm using the ArcMap Field Calculator to parse the year from a field GLVertra_1 with values like this:

1992/05/13

or more generally YYYY/MM/DD, but also containing empty cells (or cells appearing empty). My approach is JAHRNU = stringToInt( !GLVertra_1! ) with the function:

def stringToInt(s):
  if not s:
    return 0
  else:
    return int(s[0:4])

This results in the error invalid literal for int() with base 10:, which I assumed comes from empty strings, so I introduced the check for empty strings (if not s), but it still doesn't work.

The answer here (automatic casting) doesn't work for me, if I don't cast it explicitly as int(), I get an error (The value type is incompatible with the field type)

0
1

The problem is, that the cells may appear empty, but actually have "spaces" in them (" "). Extending the check for empty strings according to answers here (scroll down for more elaborate answers than the accepted one) accomodates for this case.

This worked:

def stringToInt(s):
  if not bool(s and not s.isspace()):
    return 0
  else:
    return int(s[0:4])

The explicit typecast int() can also be omitted, ArcPy/ArcMap does the casting itself.

1
  • 1
    You could also use try/except
    – BERA
    Jun 9 at 17:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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