Search code examples
pythonasciicircular-listalphabet

How to create a circular Alphabet in Python so that the letter after z is a and the letter before a is z


Is there a Function in Python to easily create a circular Alphabet, so that the letter after z is a and the letter before a is z?

I tried something with chr() and .join(Alphabet), but that didn't worked because i got the error message an integer is required (got type str).

for character in word:
    if chr(Alphabet[Alphabet.find(character)) >= "z":
        new_Alphabet = Alphabet.join(Alphabet)
    elif chr(Alphabet[Alphabet.find(character)) <= "a":
        new_Alphabet = Alphabet.join(Alphabet[:-1])

Solution

  • Use itertools.cycle ans string.ascii_lowercase:

    from itertools import cycle
    import string
    circular_alphabet = cycle(string.ascii_lowercase)
    

    That is an infinite iterator with the lowercase letters:

    >>> "".join(next(circular_alphabet ) for _ in range(50))
    'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwx'