0

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?

5
  • 1
    isdigit() checks whether the entire thing is a number, not whether a part of it is. So even if your strings contain numbers it would never return true, they have to be exclusively numbers. I think your best best would be to look at regular expressions. See here. Commented Feb 9, 2015 at 12:33
  • With the for loop (for s in test) I check every character separately whether is numeric or not. Commented Feb 9, 2015 at 12:44
  • 1
    Please always include the text, not just picture, for error messages to aid future searches by people having the same problem.
    – PolyGeo
    Commented Feb 9, 2015 at 12:57
  • If your input string is "abc123.456de789", you will return 123456789. Is that what you want? Furthermore, you are returning this as a string, not a number.
    – Llaves
    Commented Feb 9, 2015 at 15:36
  • yes this is what i want , Commented Feb 9, 2015 at 19:05

3 Answers 3

3

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
0
3

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
1
  • Thank you for your point, I omitted that, unfortunately no success, the error message i get now is 539 Commented Feb 9, 2015 at 13:37
1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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