Posted By

magicrebirth on 12/22/09


Tagged

list String iteration for if


Versions (?)

Python: iterating though strings and lists


 / Published in: Python
 

  1. ## The first example uses a string as the sequence to create a list of characters in the string:
  2.  
  3. >>>word = "Python"
  4. >>>list = []
  5. >>>for ch in word:
  6. >>> list.append(ch)
  7. >>>print list
  8. ['P', 'y', 't', 'h', 'o', 'n']
  9.  
  10.  
  11. ## This example uses the range() function to create a temporary sequence of integers the size of a list so the items in the list can be added to a string in order:
  12.  
  13. >>>string = ""
  14. >>>for i in range(len(list)):
  15. >>> string += list[i]
  16. >>>print string
  17. Python
  18.  
  19.  
  20.  
  21. ## This example uses the enumerate(string) function to create a temporary sequence. The enumerate function returns the enumeration in the form of (0, s[0]), (1, s[1]), and so on, until the end of the sequence string, so the for loop can assign both the i and ch value for each iteration to create a dictionary:
  22.  
  23. >>>dict = {}
  24. >>>for i,ch in enumerate(string):
  25. >>> dict[i] = ch
  26. >>>print dict
  27. {0: 'P', 1: 'y', 2: 't', 3: 'h', 4: 'o', 5: 'n'}
  28.  
  29.  
  30.  
  31. ## This example uses a dictionary as the sequence to display the dictionary contents:
  32.  
  33. >>>for key in dict:
  34. >>> print key, '=', dict[key]
  35. 0 = P
  36. 1 = y
  37. 2 = t
  38. 3 = h
  39. 4 = o
  40. 5 = n

Report this snippet  

You need to login to post a comment.