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

Question:

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])
Asked By: Kati

||

Answers:

I think you have to use circular queue. for more information please check this link.

Answered By: Ghazaleh Kharadpoor

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'
Answered By: Netwave

Alternative (old fashion?) solution:

def cycle_letter(ch,up=True):
  upper = 'A' <= ch <= 'Z'
  ch = ch.lower()
  letters = 'abcdefghijklmnopqrstuvwxyz'
  pos = letters.find(ch)
  if pos < 0: return ch
  length = len(letters)
  pos += 1 if up else length-1
  ans = letters[pos%length]
  if upper: ans = ans.upper()
  return ans

################################################################################

def cycle_string(s,up=True):
  return ''.join(cycle_letter(ch,up) for ch in s)

################################################################################

if __name__ == '__main__':    #Test
  s = cycle_string('Hello, World!')
  print(s)
  s = cycle_string(s,False)
  print(s)
Answered By: tonypdmtr

In case it helps someone, this snippet shifts a word by the desired number of spaces. (e.g. shift_word('abcdef', 12) = 'opqrst' )

def shift_word(word: str, spaces: int) -> str:
    first_ordinal = 97
    last_ordinal = 122
    alphabet_size = 26

    return ''.join(chr((ord(letter) - last_ordinal - spaces - 1) % alphabet_size + first_ordinal) for letter in word)

It simply iterates over the word letter-by-letter, applies some modulo math to calculate the right "bucket" where the letter should fall, and makes sure the result is in the boundaries of ordinals 97-122 (letters a-z)

Answered By: Piero Hernandez

I just visited a website, maybe this what you need:

enter link description here

But I do not how to make it. I hope someone in this community could help.

thanks a lot!

Answered By: Pai