Python: loop over consecutive characters?

34,621

Solution 1

You have a constant in the string module called ascii_lowercase, try that out:

>>> from string import ascii_lowercase

Then you can iterate over the characters in that string.

>>> for i in ascii_lowercase :
...     f(i)

For your pangram question, there is a very simple way to find out if a string contains all the letters of the alphabet. Using ascii_lowercase as before,

>>> def pangram(str) :
...     return set(ascii_lowercase).issubset(set(str))

Solution 2

Iterating a constant with all the characters you need is very Pythonic. However if you don't want to import anything and are only working in Unicode, use the built-ins ord() and its inverse chr().

for code in range(ord('a'), ord('z') + 1):
     print chr(code)

Solution 3

You've got to leave the Pascal-isms behind and learn Python with a fresh perspective.

>>> ascii_lowercase
'abcdefghijklmnopqrstuvwxyz'
>>> def pangram( source ):
    return all(c in source for c in ascii_lowercase)

>>> pangram('hi mom')
False
>>> pangram(ascii_lowercase)
True

By limiting yourself to what Pascal offered, you're missing the things Python offers.

And... try to avoid reduce. It often leads to terrible performance problems.


Edit. Here's another formulation; this one implements set intersection.

>>> def pangram( source ):
>>>     notused= [ c for c in ascii_lowercase if c not in source ]
>>>     return len(notused) == 0

This one gives you a piece of diagnostic information for determining what letters are missing from a candidate pangram.

Solution 4

A more abstract answer would be something like:

>>> x="asdf"
>>> for i in range(len(x)):
...     print x[i]

Solution 5

Hacky

method_1 = [chr(x) for x in range(ord('a'), ord('z')+1)]
print(method_1)

Neat

# this is the recommended method generally 
from string import ascii_lowercase  
method_2 = [x for x in ascii_lowercase]
print(method_2)
Share:
34,621
Admin
Author by

Admin

Updated on July 29, 2021

Comments

  • Admin
    Admin almost 3 years

    In Python (specifically Python 3.0 but I don't think it matters), how do I easily write a loop over a sequence of characters having consecutive character codes? I want to do something like this pseudocode:

    for Ch from 'a' to 'z' inclusive: #
        f(Ch)
    

    Example: how about a nice "pythonic" version of the following?

    def Pangram(Str):
        ''' Returns True if Str contains the whole alphabet, else False '''
        for Ch from 'a' to 'z' inclusive: #
            M[Ch] = False
        for J in range(len(Str)):
            Ch = lower(Str[J])
            if 'a' <= Ch <= 'z':
                M[Ch] = True
        return reduce(and, M['a'] to M['z'] inclusive) #
    

    The lines marked # are pseudocode. Of course reduce() is real Python!

    Dear wizards (specially old, gray-bearded wizards), perhaps you can tell that my favorite language used to be Pascal.