Main Content

Strings as collections in Python

Archive - Originally posted on "The Horse's Mouth" - 2009-07-12 17:30:54 - Graham Ellis

In Python, I can treat a string as a collection of characters and iterate through it without the need to do any sort of conversion on it, or muck about with "substr" ...

breakfast = "Croissants and toast"
 
for letter in breakfast:
   print "Give me a ",letter
 
print "and we have",breakfast


Dorothy-2:py grahamellis$ python sar2
Give me a C
Give me a r
Give me a o
Give me a i
Give me a s
Give me a s
Give me a a
Give me a n
Give me a t
Give me a s
Give me a
Give me a a
Give me a n
Give me a d
Give me a
Give me a t
Give me a o
Give me a a
Give me a s
Give me a t
and we have Croissants and toast
Dorothy-2:py grahamellis$