Generators can only yield ints?
Steven D'Aprano
steve at REMOVE-THIS-cybersource.com.au
Fri Aug 22 20:52:14 EDT 2008
On Fri, 22 Aug 2008 15:44:15 -0700, defn noob wrote:
> def letters():
> a = xrange(ord('a'), ord('z')+1)
> B = xrange(ord('A'), ord('Z')+1)
> while True:
> yield chr(a)
> yield chr(B)
>
>
>>>> l = letters()
>>>> l.next()
>
> Traceback (most recent call last):
> File "<pyshell#225>", line 1, in <module>
> l.next()
> File "<pyshell#223>", line 5, in letters
> yield chr(a)
> TypeError: an integer is required
>>>>
>>>>
>
> Any way to get around this?
Yes, write code that isn't buggy :)
Generators can return anything you want. Your problem is that you're
passing an xrange object to chr() instead of an int. Try this:
def letters():
a = xrange(ord('a'), ord('z')+1)
B = xrange(ord('A'), ord('Z')+1)
for t in zip(a, B):
yield chr(t[0])
yield chr(t[1])
But (arguably) a better way is:
def letters():
from string import ascii_letters as letters
for a,b in zip(letters[0:26], letters[26:]):
yield a
yield b
Note that it is important to use ascii_letters rather than letters,
because in some locales the number of uppercase and lowercase letters
differ.
--
Steven
More information about the Python-list
mailing list