How do I iterate through the alphabet?

PythonPython 2.7Alphabet

Python Problem Overview


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

I want to iterate through URLs that have the 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 format.

Python Solutions


Solution 1 - Python

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

>>> from string import ascii_lowercase
>>> for c in ascii_lowercase:
...     # append to your url

Solution 2 - Python

In addition to string.ascii_lowercase you should also take a look at the ord and chr built-ins. ord('a') will give you the ascii value for 'a' and chr(ord('a')) will give you back the string 'a'.

Using these you can increment and decrement through character codes and convert back and forth easily enough. ASCII table is always a good bookmark to have too.

Solution 3 - Python

shortest way

for c in list(map(chr,range(ord('a'),ord('z')+1))):
    do_something(base_url+c)

iterate function

def plusplus(oldChar):
     return chr(ord(oldChar)+1)
plusplus('a') # output - b

Another option

url=www.website.com/term
my_char=ord('a') # convert char to ascii
while my_char<= ord('z'):
   my_char+=1 # iterate over abc
   my_url=url+chr(my_char)  # convert ascii to char
   do_something(my_url)

Based on @Brian answer.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMillsOnWheelsView Question on Stackoverflow
Solution 1 - PythonJaredView Answer on Stackoverflow
Solution 2 - PythonBrianView Answer on Stackoverflow
Solution 3 - PythonyoniloboView Answer on Stackoverflow