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.
A:
You can multiply the string in the integer. For example
>>> 'a' * 2
'aa'
>>> 'a' * 4
'aaaa'
>>> 'z' * 3
'zzz'
>>> 'az' * 3
'azazaz'
Adam
2010-05-14 23:38:01
yes, but i want to run through all the permutations
calccrypto
2010-05-14 23:38:58
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
2010-05-14 23:43:00
correct. all the way until the string is x chars long
calccrypto
2010-05-14 23:48:03
A:
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
2010-05-14 23:40:53
+4
A:
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
2010-05-14 23:49:34
A:
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
2010-05-15 08:25:29