Fix Python – How do I iterate through the alphabet?

Question

Asked By – MillsOnWheels

  1. In Python, could I simply ++ a char?
  2. What is an efficient way of doing this?

I want to iterate through URLs and generate them in the following way:

www.website.com/term/#
www.website.com/term/a
www.website.com/term/b
www.website.com/term/c
www.website.com/term/d ... 
www.website.com/term/z 

Now we will see solution for issue: How do I iterate through the alphabet?


Answer

You can use string.ascii_lowercase which is simply a convenience string of lowercase letters,

Python 2 Example:

from string import ascii_lowercase

for c in ascii_lowercase:
    # append to your url

Python 3 Example:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from string import ascii_lowercase as alc
for i in alc:
    print(f"www.website.com/term/{i}")

# Result
# www.website.com/term/a
# www.website.com/term/b
# www.website.com/term/c
# ...
# www.website.com/term/x
# www.website.com/term/y
# www.website.com/term/z

Or if you want to keep nesting you can do like so:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
for i in alc:
    print(f"www.website.com/term/{i}")
    for j in alc:
        print(f"www.website.com/term/{i}{j}")

# Result
# www.website.com/term/a
# www.website.com/term/aa
# www.website.com/term/ab
# www.website.com/term/ac
# ...
# www.website.com/term/ax
# www.website.com/term/ay
# www.website.com/term/az
# www.website.com/term/b
# www.website.com/term/ba
# www.website.com/term/bb
# www.website.com/term/bc
# ...
# www.website.com/term/bx
# www.website.com/term/by
# www.website.com/term/bz
# www.website.com/term/c
# www.website.com/term/ca
# www.website.com/term/cb
# www.website.com/term/cc
# ...
# ...
# ...
# www.website.com/term/z
# www.website.com/term/za
# www.website.com/term/zb
# www.website.com/term/zc
# www.website.com/term/zd
# ...
# www.website.com/term/zx
# www.website.com/term/zy
# www.website.com/term/zz

This question is answered By – Jared

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0