TransWikia.com

Extracting numbers from string field using Python Parser of ArcMap Field Calculator?

Geographic Information Systems Asked by Stelios Tselepis on February 12, 2021

enter image description here

I am trying to calculate field test2 with only the numeric values from a string field test. The entire script is like:


def makestr(test)
     list=[]
     for s in test:
         if s.isdigit():
             list.append(s)
     for a in list:
         str=''.join(list)

But I keep getting an error:

enter image description here

Any ideas?

3 Answers

You are defining the function on the first statement, which needs to end in a ":", e.g.

def makestr(test):

Here is a simple solution:

def makestr(test): 
  try:
    return ''.join(i for i in test if i.isdigit()) 
  except ValueError:
    pass

Answered by artwork21 on February 12, 2021

I found also another error. You have to join the a values at the last loop:

def makestr(test):
    l1=[]
    for val in test:
        if val.isdigit():
            l1.append(val)
    return " ".join(l1)

or

def makestr(test):
    l1 =[val for val in test if val.isdigit()]
    return " ".join(l1)

You can join list items without iterating over them. Just use the join fuction with the list as argument. It is better not to name variables "str" or "list" because thay are python built-in names, which can cause problems.

Answered by Martin on February 12, 2021

Try this:

def makestr(test):  # Add colon
     numlist = []   # Don't use name "list"
     for s in test:
         if s.isdigit():
             numlist.append(s)
     return ''.join(numlist)  # Return a value

Answered by nmpeterson on February 12, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP