Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I iterate through a string in Python?

Tags:

python

As an example, lets say I wanted to list the frequency of each letter of the alphabet in a string. What would be the easiest way to do it?

This is an example of what I'm thinking of... the question is how to make allTheLetters equal to said letters without something like allTheLetters = "abcdefg...xyz". In many other languages I could just do letter++ and increment my way through the alphabet, but thus far I haven't come across a way to do that in python.

def alphCount(text):   lowerText = text.lower()   for letter in allTheLetters:       print letter + ":", lowertext.count(letter) 
like image 592
Lawrence Johnston Avatar asked Oct 23 '08 06:10

Lawrence Johnston


People also ask

Can you iterate through a string with a for loop Python?

Use the for Loop to Loop Over a String in Python The for loop is used to iterate over structures like lists, strings, etc. Strings are inherently iterable, which means that iteration over a string gives each character as output.

How do you iterate over a string in Python?

You can traverse a string as a substring by using the Python slice operator ([]). It cuts off a substring from the original string and thus allows to iterate over it partially. To use this method, provide the starting and ending indices along with a step value and then traverse the string.

How do I iterate through a string?

For loops with strings usually start at 0 and use the string's length() for the ending condition to step through the string character by character. String s = "example"; // loop through the string from 0 to length for(int i=0; i < s. length(); i++) { String ithLetter = s.

Are strings iterable in Python?

An iterable is any Python object capable of returning its members one at a time, permitting it to be iterated over in a for-loop. Familiar examples of iterables include lists, tuples, and strings - any such sequence can be iterated over in a for-loop.


2 Answers

The question you've asked (how to iterate through the alphabet) is not the same question as the problem you're trying to solve (how to count the frequency of letters in a string).

You can use string.lowercase, as other posters have suggested:

import string allTheLetters = string.lowercase 

To do things the way you're "used to", treating letters as numbers, you can use the "ord" and "chr" functions. There's absolutely no reason to ever do exactly this, but maybe it comes closer to what you're actually trying to figure out:

def getAllTheLetters(begin='a', end='z'):     beginNum = ord(begin)     endNum = ord(end)     for number in xrange(beginNum, endNum+1):         yield chr(number) 

You can tell it does the right thing because this code prints True:

import string print ''.join(getAllTheLetters()) == string.lowercase 

But, to solve the problem you're actually trying to solve, you want to use a dictionary and collect the letters as you go:

from collections import defaultdict     def letterOccurrances(string):     frequencies = defaultdict(lambda: 0)     for character in string:         frequencies[character.lower()] += 1     return frequencies 

Use like so:

occs = letterOccurrances("Hello, world!") print occs['l'] print occs['h'] 

This will print '3' and '1' respectively.

Note that this works for unicode as well:

# -*- coding: utf-8 -*- occs = letterOccurrances(u"héĺĺó, ẃóŕĺd!") print occs[u'l'] print occs[u'ĺ'] 

If you were to try the other approach on unicode (incrementing through every character) you'd be waiting a long time; there are millions of unicode characters.

To implement your original function (print the counts of each letter in alphabetical order) in terms of this:

def alphCount(text):     for character, count in sorted(letterOccurrances(text).iteritems()):         print "%s: %s" % (character, count)  alphCount("hello, world!") 
like image 197
Glyph Avatar answered Oct 18 '22 17:10

Glyph


the question is how to make allTheLetters equal to said letters without something like allTheLetters = "abcdefg...xyz"

That's actually provided by the string module, it's not like you have to manually type it yourself ;)

import string  allTheLetters = string.ascii_lowercase  def alphCount(text):   lowerText = text.lower()   for letter in allTheLetters:       print letter + ":", lowertext.count(letter) 
like image 45
Matthew Trevor Avatar answered Oct 18 '22 17:10

Matthew Trevor