Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

range over character in python

Is there an way to range over characters? something like this.

for c in xrange( 'a', 'z' ):
    print c

I hope you guys can help.

like image 396
huan Avatar asked Aug 09 '11 18:08

huan


People also ask

How do you find the range of a character in a string in Python?

You can get a range of characters(substring) by using the slice function. Python slice() function returns a slice object that can use used to slice strings, lists, tuples. You have to Specify the parameters- start index and the end index, separated by a colon, to return a part of the string.

What does range () do in Python?

The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and stops before a specified number.

Can you loop through 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.


2 Answers

This is a great use for a custom generator:

Python 2:

def char_range(c1, c2):     """Generates the characters from `c1` to `c2`, inclusive."""     for c in xrange(ord(c1), ord(c2)+1):         yield chr(c) 

then:

for c in char_range('a', 'z'):     print c 

Python 3:

def char_range(c1, c2):     """Generates the characters from `c1` to `c2`, inclusive."""     for c in range(ord(c1), ord(c2)+1):         yield chr(c) 

then:

for c in char_range('a', 'z'):     print(c) 
like image 181
Ned Batchelder Avatar answered Sep 28 '22 07:09

Ned Batchelder


import string
for char in string.ascii_lowercase:
    print char

See string constants for the other possibilities, including uppercase, numbers, locale-dependent characters, all of which you can join together like string.ascii_uppercase + string.ascii_lowercase if you want all of the characters in multiple sets.

like image 20
agf Avatar answered Sep 28 '22 05:09

agf