Need help with field calculator.

468
7
03-11-2024 09:10 AM
EGardner7
New Contributor II

I am trying to use field calculator to move numbers to the front of a value. For example, Apple Dr. 245 to 245 Apple Dr. I have tried a bunch of different python scripts that are AI generated but I can't get it to work. Does anyone know why I could be having issues with this? Here is one script I tried for example: 

def move_numbers_to_front(value):
words = value.split()
if len(words) > 1 and words[-1].isnumeric():
return f"{words[-1]} {' '.join(words[:-1])}"
return value

# Usage: move_numbers_to_front(!CableName!)

Tags (2)
0 Kudos
7 Replies
DanPatterson
MVP Esteemed Contributor

indentation perhaps

a = "Apple Dr. 245"

def move_numbers_to_front(value):
    words = value.split()
    if len(words) > 1 and words[-1].isnumeric():
        return f"{words[-1]} {' '.join(words[:-1])}"
    return value
    

move_numbers_to_front(a)
'245 Apple Dr.'

... sort of retired...
EGardner7
New Contributor II

Unfortunately that didn't work. Thank you though!

0 Kudos
JoshuaBixby
MVP Esteemed Contributor

Comments like "that didn't work" aren't helpful.  If there was an error, what exactly was the error, and provide a traceback if one exists.  If there was no error but the results are unexpected, state what you expected and what you got.

0 Kudos
DanPatterson
MVP Esteemed Contributor

Then you might want to provide the error message.  Perhaps, you have some null values in the field or other issues with the contents of the field


... sort of retired...
EGardner7
New Contributor II

Yes there are null values in the field. How do I get it to ignore those? The error message is: There was a failure during processing, check the Geoprocessing Results window for details.

0 Kudos
DanPatterson
MVP Esteemed Contributor

perhaps

a = None
def move_numbers_to_front(value):
    if value is None:
        return
    words = value.split()
    if len(words) > 1 and words[-1].isnumeric():
        return f"{words[-1]} {' '.join(words[:-1])}"
    return value
    

print(move_numbers_to_front(a))
None

... sort of retired...
DanPatterson
MVP Esteemed Contributor

did it work? or were there other issues?


... sort of retired...
0 Kudos