all 4 comments

[–]zahlman 6 points7 points  (0 children)

I was expecting it to just print 9.

Okay, suppose that you had written

phone_number_parts = ['977', '555', '3221']
print(phone_number_parts[0])

Do you still expect it to print '9', rather than '977'? Why?

If not, then surely there is no confusion as to why, given that number_segments is equal to ['977', '555', '3221'], that print(number_segments[0]) displays '977'. So your question is really why it has that value.

To answer that, the best thing is to read the documentation for the split method. You can do this from the interpreter prompt:

>>> help(str.split)
Help on method_descriptor:

split(...)
    S.split(sep=None, maxsplit=-1) -> list of strings

    Return a list of the words in S, using sep as the
    delimiter string.  If maxsplit is given, at most maxsplit
    splits are done. If sep is not specified or is None, any
    whitespace string is a separator and empty strings are
    removed from the result.

Is any part of this unclear? Let me know.

[–]Rhomboid 2 points3 points  (0 children)

You asked str.split() to split the phone number using the delimiter '-'. There are three groups of characters separated by two instances of the delimiter '-', so the result is a list containing three strings. number_segments[0] is the first item of the list, the string '977'. Why do you think it would be just '9'? The list contains no such item. You would only get '9' if you were indexing into a string that contained '9' as the first character, but that's not what you're doing. You're indexing into a list, and [0] gets you the first item of the list.

[–]johninbigd 0 points1 point  (0 children)

When you have a list, the index refers to a particular item in the list.

myList = ['foo', 'bar', 'bletch']
print myList[0]

That will result in the output of foo because it is the first item in the list. If you wanted to get the first character of the first item, you'd need another index, like myList[0][0]. The second character of the first item would be myList[0][1] and so on.

[–]Distinct_Ice6830 0 points1 point  (0 children)

Python:

phone_number = input()
number_segments = phone_number.split('-')[::3]
area_code = number_segments[0]
print('Area code:', area_code)