Frage

Is there's a function like change_alphabetical($string,$number) that changes every letter in $string, $number times forward?

EXAMPLE

print change_alphabetical("abc",2)

prints:

"cde"

OR

change_alphabetical("abc",-1)

prints:

zab
War es hilfreich?

Lösung

import string

def change(word, pos):
    old = string.ascii_lowercase
    new = old[pos:] + old[:pos]
    return word.translate(string.maketrans(old, new))

Andere Tipps

I'm not aware of any builtin that does this, but you can roll your own:

def change(string, position):
    alphabet = "abcdefghijklmnopqrstuvwxyz"
    indexes = [alphabet.find(char) for char in string]
    new_indexes = [(i + position) % 26 for i in indexes]
    output = ''.join([alphabet[i] for i in new_indexes])
    return output

print change("abc", -1)  # zab

It essentially takes each character in the input string, and converts it to a numerical position using the some_list.find() method. It then adds the offset, mod 26, to get the new index and subsequently the new string.

Keep in mind that this works only with lowercase letters (although you could always do string = string.lower()), and will need to be adjusted if you want to use different alphabet besides the English one.


If you do want the code to work internationally, you could use the locale module to get the local alphabet given some arbitrary language:

import locale
locale.setlocale(locale.LC_ALL, '')

import string

def change(string, position):
    alphabet = string.lowercase
    indexes = [alphabet.find(char) for char in string.lower()]
    new_indexes = [(i + position) % len(alphabet) for i in indexes]
    output = ''.join([alphabet[i] for i in new_indexes])
    return output

Currently, this simply gets the alphabet of whatever local the current computer is set to. I believe you can change the underlying language by editing the second argument in locale.setlocale.

The string.lowercase attribute will then return all the lowercase letters of the given language, in order.

Keep in mind that locale.setlocale is not considered thread-safe, and will apply to the entire program.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top