I need to strip numbers from certain fields. I have the following but it strips all number from the entire table.
Some of these fields have blanks and nulls.
import arcpy
arcpy.env.overwriteOutput = True
table = "C:/temp/EMS_Table"
field = ['Agency', 'fa', 'lz']
for field in [f.name for f in arcpy.Describe(table).fields if f.type == "String"]:
exp = "!{0}!.strip('0123456789.- ')"
arcpy.management.CalculateField(table, field, exp.format(field), "PYTHON")
You are overwriting the list of fields when you create the loop.
Consider:
field = ['Agency', 'fa', 'lz']
for field in [1, 2, 3, 4]:
print(field)
1
2
3
4
If you know the fields you want to loop through:
fields = ['Agency', 'fa', 'lz']
for field in fields:
print(field)
Agency
fa
lz
field gets defined twice, once in line 7 … which are the fields that you want I presume.... but it gets redefined again in line 8 in the 'for field....' section. I suspect that it is not just doing the fields you want but all the fields that are of type 'String'
yes it's doing all the fields, not really sure how to write it. I am also not sure if this is the best way. would using with arcpy.da.UpdateCursor better?
I think there is some confusion about whether you are trying to strip stuff from values in a field, or strip the fields (which are weirdly names, hence the suspicion) that you have listed.
If we assume your fields are as listed in line 1 and assuming you are working on a copy and that your calculatefield expression actually works... maybe
field = ['Agency', 'fa', 'lz']
for f in field:
exp = "!{0}!.strip('0123456789.- ')"
arcpy.management.CalculateField(table, f, exp.format(field), "PYTHON")
Now if those aren't the fields, maybe you might want to show with a screen grab what you are working with
I am trying to strip from the number values in those fields. sorry for not making it clear.
i am getting ERROR 000539: Invalid field['Agency', 'fa', 'lz']
arcpy.management.CalculateField(table, f, exp.format(f), "PYTHON")
Can you show what the field values look like at present? Is there a pattern of how they are formatted like
FA25 or FA 25 ?
When you follow some sort of naming convention in your field values it's always easier to parse them out when you need to...
I think for the most part they are just FA25 with no spaces.
I stole this from StackOverflow: python - Removing numbers from string - Stack Overflow
no_digits = []
# Iterate through the string, adding non-numbers to the no_digits list
for i in s:
if not i.isdigit():
no_digits.append(i)
# Now join all elements of the list with '',
# which puts all of the characters together.
result = ''.join(no_digits)
Where s = your field value....
edited- just to add, you could do the inverse, and look for and keep letters....
is_alpha =[]
for i in s:
if i.isalpha():
is_alpha.append(i)