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.
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.
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.
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.
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With