what's a simple way to increase the length of a string to an arbitrary integer x? like 'a' goes to 'z' and then goes to 'aa' to 'zz' to 'aaa', etc.
Asked
Active
Viewed 2,939 times
6
-
Where does `x` come in? Like if the string is "abc" and `x` is 4, the string becomes "abg"? – Michael Mrozek May 14 '10 at 23:36
-
oops. i meant to say the string becomes x long, so if x = 4, the strings would be 'aaaa'... 'zzzz' – calccrypto May 14 '10 at 23:38
-
Somewhat related, see [this code golf](http://stackoverflow.com/questions/2634427/code-golf-numeric-equivalent-of-an-excel-column-name/). – Mark Rushakoff May 15 '10 at 12:36
4 Answers
7
That should do the trick:
def iterate_strings(n):
if n <= 0:
yield ''
return
for c in string.ascii_lowercase:
for s in iterate_strings(n - 1):
yield c + s
It returns a generator. You can iterate it with a for loop:
for s in iterate_strings(5)
Or get a list of the strings:
list(iterate_strings(5))
If you want to iterate over shorter strings too, you can use this function:
def iterate_strings(n):
yield ''
if n <= 0:
return
for c in string.ascii_lowercase:
for s in iterate_strings(n - 1):
yield c + s

Adam
- 851
- 6
- 10
3
Here's my solution, similar to Adam's, except it's not recursive. :]
.
from itertools import product
from string import lowercase
def letter_generator(limit):
for length in range(1, limit+1):
for letters in product(lowercase, repeat=length):
yield ''.join(letters)
And it returns a generator
, so you can use a for
loop to iterate over it:
for letters in letter_generator(5):
# ...
Have fun!
(This is the second time today I found itertools.product()
useful. Woot.)

Xavier Ho
- 17,011
- 9
- 48
- 52
0
You can multiply the string in the integer. For example
>>> 'a' * 2
'aa'
>>> 'a' * 4
'aaaa'
>>> 'z' * 3
'zzz'
>>> 'az' * 3
'azazaz'

Adam
- 851
- 6
- 10
-
Let's see if I get you right: You want to iterate over all the strings between 'aaaa' and 'zzzz', ('aaaa', 'aaab', 'aaac', .... 'zzzz'). – Adam May 14 '10 at 23:43
0
Define x. I am using x = 5
for this example.
x = 5
import string
for n in range(1,x+1):
for letter in string.ascii_lowercase:
print letter*n

tdedecko
- 1,442
- 10
- 15
-
You might want to set the start value of the range statement since the very first thing printed using that code is 26 lines of blanks because you're doing `letter*0` at first. – Dustin May 14 '10 at 23:44