-6

In the below code, how does Python know to print each letter individually? I really can't wrap my head around it.

for letter in 'Python':
   print 'Current Letter :', letter

It knows to split the string 'Python' into 6 individual strings. How does it do that?

TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97

3 Answers3

1

The easiest way for me to think about this is to remember that the word 'letter' could easily be replaced with anything you want to call it, it's just a placeholder.

To illustrate, let's replace 'letter' in your loop with the name 'Dave'.

for Dave in 'Python':
    print 'Current letter : ', Dave

There is no 'Dave' in the string Python. But this will still print out every letter in the string 'Python'. That is because when you setup your loop to iterate over a string, as you've done here, you are telling python that whatever you want it to do, in this case 'print', needs to be done to every item in the string.

for stuff in 'my_string':
    do stuff to every letter in my_string

Also, since you're new to StackExchange, welcome. Since there are so many questions to be answered, to save everyone time, it works best if you do a very thorough google search to find out if an answer exists before posting a question on here. I'm sure there are a lot of good resources out there that will help you understand these concepts! Best of luck.

SummerEla
  • 1,902
  • 3
  • 26
  • 43
  • 1
    Thanks! That's very clear, and thanks for the advice re: googling! I'm finding that my knowledge is so basic that it's hard to google effectively right now, I'm sure I'll get there though! – ClennersIII Sep 08 '15 at 19:22
0

A string is a sequence of single character strings. So when you iterate it you get each single character string in the sequence. You can also use indexes and slicing operations as per other sequence types.

Chad S.
  • 6,252
  • 15
  • 25
0

How does Python do it? As such:

>>> import dis
>>> def f(text):
...     for letter in text:
...             print(letter)
...
>>> dis.dis(f)
  2           0 SETUP_LOOP              24 (to 27)
              3 LOAD_FAST                0 (text)
              6 GET_ITER
        >>    7 FOR_ITER                16 (to 26)
             10 STORE_FAST               1 (letter)

  3          13 LOAD_GLOBAL              0 (print)
             16 LOAD_FAST                1 (letter)
             19 CALL_FUNCTION            1 (1 positional, 0 keyword pair)
             22 POP_TOP
             23 JUMP_ABSOLUTE            7
        >>   26 POP_BLOCK
        >>   27 LOAD_CONST               0 (None)
             30 RETURN_VALUE

However, the important lesson here is simply that iterating over a sequence (like a string) or other iterable allows you to work with each of that iterable's elements (individual characters, in this case).

TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97