I am trying to Field Calc the integers that live in a STRING field for roads. The client only wants the numbers of each road and not any of the text. I have tried : def comp(x):
return any(i.isdigit() for i in x)
No real results. This finds a number and returns "1" if true and "0" if false. What I need is for the entire number, say 100th Street, would become 100. Any help would be much appreciated.
Several ways to go about it depending on how clean and/or complicated the data are in text fields. You can use itertools.takewhile() or just adopt the pseudo-code from it.
can you provide an example with the snippet given?
Using the pseudo-code directly from page I link to:
# Codeblock
def takewhile(predicate, iterable):
for x in iterable:
if predicate(x):
yield x
else:
break
# Expression
"".join(takewhile(str.isdigit, !FULLNAME!))
"any" is used to return a boolean, in this case 1/True that there was a number in the field.
If you want the number then
a = '100 some street'
"".join([i for i in a if i.isdigit()])
'100'
It will continue to return numbers whether they make sense or not like
a = "100 1st ave apt 5"
will return "10015"
which would require some extra work to just get the street address
a = "100 1st ave apt 5"
# -- getting there
"".join([i for i in a if i.isdigit() or i == " "])
'100 1 5'
# -- split the string and slice the part you want
"".join([i for i in a if i.isdigit() or i == " "]).split(" ")[0]
Out[5]: '100'
So examine and modify your use case to avoid such things
Another one
Code Block
def comp(x):
numlist = [i for i in x if i.isdigit()]
if len(numlist)>0:
return int(''.join(numlist))
Expression:
comp( !NUMBER_STRING! )
As Dan already mentioned, this general approach will fail when there are other number sequences in the string. For example, an address like "100 South 900 West" will return "100900" with this approach.
This is another good use case for my Idea for Esri to Add Python Regular Expression (re) Helpers to Calculate Field Dialog . Even without the "Helper" functions, you can still use re - Regular expression operations - Python 3 documentation by just importing the module in the code block:
# Codeblock
import re
# Expression
re.match(r"^\s*\d*", !FULLNAME!).group()