Solved! Go to Solution.
cleanedValue = ''.join([i for i in fieldValue if i.isdigit()])
import string fieldValue = "ML-26588" for character in fieldValue: if character in string.ascii_letters or character in string.punctuation: fieldValue = fieldValue.replace(character, "") print fieldValue
#Removes all letters and special characters from a string - hopefully leaving only numbers. import string, arcpy updateRows = arcpy.UpdateCursor(myFC) for updateRow in updateRows: fieldValue = updateRow.MY_FIELD for character in fieldValue: if character in string.ascii_letters or character in string.punctuation: fieldValue = fieldValue.replace(character, "") updateRows.updateRow(updateRow) del updateRow, updateRows
import string fieldValue = "ML-26588-12-a" stripChars = fieldValue.translate(None, string.digits) fieldValue = fieldValue.translate(None, stripChars) print stripChars print fieldValueprints:
ML---a 2658812
cleanedValue = ''.join([i for i in fieldValue if i.isdigit()])
Thanks, Mike! It was an agonizing quest before I found your simple answer!
Eric
Mike, or anyone, are you still out there? Your solution worked perfectly for me in a field calculation a couple days ago. Now, using the same fields in the same database, but a different selection of records, I'm getting an error. I'm too much of a dolt in Python to see why. Here's what I'm getting:
"syntaxerror: encoding declaration in unicode string (<expression>, line 0)" (see below)
At first I thought it might be some characters that were causing the issue (hyphens, slashes, spaces), but eliminating them didn't help.
Any ideas?
Eric
... and then tell me how to apply it to the code block on Calculate Field GP tool.
ExtractNum(!INFIELD!)
def ExtractNum(fieldValue): try: val = ''.join([i for i in fieldValue if i.isdigit()]) except: val = None return val
A simple 1 liner will do it:cleanedValue = ''.join([i for i in fieldValue if i.isdigit()])
good luck,
Mike