Mid() function in Python

36629
11
10-31-2019 10:55 AM
SLouq
by MVP Regular Contributor
MVP Regular Contributor

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

Tags (2)
0 Kudos
11 Replies
JoeBorgione
MVP Emeritus

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...

That should just about do it....
0 Kudos
SLouq
by MVP Regular Contributor
MVP Regular Contributor

how do I use that expression on a Field in ArcGIS Pro so it returns values starting at the 5th character?

0 Kudos
DanPatterson_Retired
MVP Emeritus

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
JoeBorgione
MVP Emeritus

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 

That should just about do it....
DanPatterson_Retired
MVP Emeritus

as per the lesson... 'b' is anything

like str(!STR_NAME!)[5:20]

SLouq
by MVP Regular Contributor
MVP Regular Contributor

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.

0 Kudos
JoeBorgione
MVP Emeritus

Sometimes you just need to fiddle with the indexes to get it just right...

That should just about do it....
0 Kudos
SLouq
by MVP Regular Contributor
MVP Regular Contributor

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.

0 Kudos
JoeBorgione
MVP Emeritus

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....

That should just about do it....