Kati
Kati

Reputation: 41

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])

Upvotes: 1

Views: 2562

Answers (4)

Piero Hernandez
Piero Hernandez

Reputation: 455

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)

Upvotes: 0

tonypdmtr
tonypdmtr

Reputation: 3225

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)

Upvotes: 0

Netwave
Netwave

Reputation: 42678

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'

Upvotes: 3

Ghazaleh Kharadpoor
Ghazaleh Kharadpoor

Reputation: 146

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

Upvotes: 0

Related Questions