I am trying to use the Python Mid() function to return strings starting at the 5th character.
I have tried
!STR_NAME!.Mid(5:20)
but that gives me a traceback error
Can someone point me in the right direction?
Thanks
Never heard of the mid() functin and couldn't find it with dr. google.
myString = 'abcdefghijklmnopqrstuvwxyz'
x = myString[5:20]
print(x)
#returns 'fghijklmnopqrst'
This works for me...
how do I use that expression on a Field in ArcGIS Pro so it returns values starting at the 5th character?
Slice lesson
# ---- python slicing...
b = "abcdefghijklmnopqrstuvwxyz"
str(b)[5:20]
'fghijklmnopqrst'
str(b)[5:]
'fghijklmnopqrstuvwxyz'
str(b)[-5:]
'vwxyz'
str(b)[:5]
'abcde'
# ---- why use str????
str(None)[:2]
'No'
None[:2]
Traceback (most recent call last):
File "<ipython-input-18-5a2d59b27828>", line 1, in <module>
None[:2]
TypeError: 'NoneType' object is not subscriptable
See Dan's suggestions below... or:
str(!FieldName!)[5:20]
resources for you: Cutting and slicing strings in Python - Python Central , Python str() - Python Standard Library
as per the lesson... 'b' is anything
like str(!STR_NAME!)[5:20]
Thanks guys! I got it to execute but it erased more chars than I wanted. Now I just have to re run the models and change the parameters around when I get to this point.
Sometimes you just need to fiddle with the indexes to get it just right...
That program is buggy as hell. I started my whole model again from the beginning and it stopped when it got to this part with the same error
but yet it worked when I tried it while we were discussing in this thread.
Indexes can have a sense of humor. Consider:
myString = 'abcdefg'
str(myString)[1:3]
#'bc' what I really wanted was 'bcd' so what I should have used is:
str(myString)[1:4]
#'bcd'
len(myString)
#7
myString[7]
#Traceback (most recent call last):
#File "<ipython-input-12-4e9d2e9a673c>", line 1, in <module>
#myString[7]
#IndexError: string index out of range
When you want specific characters out of a string, you need to really consider which ones you want....