ghost
ghost

Reputation: 39

Need a little help understanding this line "[i:i+12]"

I'm following Automate the Boring Stuff with Python, and I'm doing an exercise that searches for a phone number format (###-###-####) within a group of text. This piece of code is what searches for the pattern: [i:i+12] and I need a little help understanding how it works.

def isPhoneNumber(text):
    if len(text) != 12:
        return False
    for i in range(0, 3):
        if not text[i].isdecimal():
            return False
        if text[3] != '-':
            return False
        for i in range(4, 7):
            if not text[i].isdecimal():
                return False
            if text[7] != '-':
                return False
            for i in range(8, 12):
                if not text[i].isdecimal():
                    return False
            return True
message = 'Call me at 415-555-1011 tomorrow. 415-555-9999 is my office.'
for i in range(len(message)):

chunk = message[i:i+12]

    if isPhoneNumber(chunk):
        print('Phone number found: ' + chunk)
print('Done')

Upvotes: 1

Views: 435

Answers (1)

ktzr
ktzr

Reputation: 1645

It is called slice notation, it allows you to cut out a bit of an array, you can treat strings a bit like arrays in python.

In your example, when i=0, message[i:i+12] will be message[0:12] this will get the 0th character of the string, up to but not including the 12, so will output "Call me at 4"

When i=1 you will have message[1:13] so will get "all me at 41"

Effectively you are checking every 12 consecutive characters in the string to see they are a phone number.

You can learn more about slices here (starts talking about slices about halfway into the strings section)

Upvotes: 2

Related Questions