1

I have a bunch of phone numbers and some contain a 1 in front of them e.g. "18885556607" and I would like to simply remove the 1. I can't just remove all first characters because there are numbers like "8665558411"


Here is the code I've tried:

def splitme(s):
    if (s[:1] == "1"):
        return s[2:]
    else: 
        return(s)

expression:

splitme( !Phone! )

The field is a string field, please let me know what I need to change.

  • 1
    Welcome to GIS SE! As a new user please take the tour to learn about our focused Q&A format. – Midavalo Jun 12 '17 at 20:24
  • 2
    This question is all but pure Python and thus better researched at Stack Overflow. – PolyGeo Jun 12 '17 at 20:26
  • Do you have to be careful with number starting with a "real" valid 1? – s.k Jun 12 '17 at 21:23
5

Python starts counting at 0.

Here's what a quick test looks like:

>>> x = '18885556607'
>>> y = '8665558411'
>>> x[0]
'1'
>>> x[1:]
'8885556607'
>>> 

So you can write your code as:

def splitme(s):
    if (s[0] == "1"):
        return s[1:]
    else: 
        return(s)
  • This solution works. However it seems odd to me that if I want to create a two new fields one for the phone number and one for the extension I need to use extension = !Phone![10:] and phone = !Phone![:10] to get the full number. If it starts counting at 0 should those not need to be changed? – jol1234 Jun 14 '17 at 14:24
  • @user3251415 Sorry I missed your comment here. In the square brackets, to the right of the colon [:10] = display up to (and not including) the character in position 10. To the left of the colon [10:] display from (and including) the character in position 10 (so it uses the first 10 characters - the one at position 10 is the 11th character). – Midavalo Jun 17 '17 at 5:14

Not the answer you're looking for? Browse other questions tagged or ask your own question.