I would like to make a alphabetical list for an application similar to an excel worksheet.
A user would input number of cells and I would like to generate list. For example a user needs 54 cells. Then I would generate
'a','b','c',...,'z','aa','ab','ac',...,'az', 'ba','bb'
I can generate the list from [ref]
from string import ascii_lowercase
L = list(ascii_lowercase)
How do i stitch it together? A similar question for PHP has been asked here. Does some one have the python equivalent?
The isalpha() method returns True if all characters in the string are alphabets. If not, it returns False.
Use itertools.product
.
from string import ascii_lowercase
import itertools
def iter_all_strings():
for size in itertools.count(1):
for s in itertools.product(ascii_lowercase, repeat=size):
yield "".join(s)
for s in iter_all_strings():
print(s)
if s == 'bb':
break
Result:
a
b
c
d
e
...
y
z
aa
ab
ac
...
ay
az
ba
bb
This has the added benefit of going well beyond two-letter combinations. If you need a million strings, it will happily give you three and four and five letter strings.
Bonus style tip: if you don't like having an explicit break
inside the bottom loop, you can use islice
to make the loop terminate on its own:
for s in itertools.islice(iter_all_strings(), 54):
print s
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