$string のすべての文字を $number 回前方に変更する change_alphabetical($string,$number) のような関数はありますか?
例
print change_alphabetical("abc",2)
プリント:
"cde"
また
change_alphabetical("abc",-1)
プリント:
zab
$string のすべての文字を $number 回前方に変更する change_alphabetical($string,$number) のような関数はありますか?
例
print change_alphabetical("abc",2)
プリント:
"cde"
また
change_alphabetical("abc",-1)
プリント:
zab
import string
def change(word, pos):
old = string.ascii_lowercase
new = old[pos:] + old[:pos]
return word.translate(string.maketrans(old, new))
これを行うビルトインは知りませんが、独自のものを作成できます。
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
基本的に、入力文字列の各文字を取得し、some_list.find()
メソッドを使用して数値位置に変換します。次に、オフセット mod 26 を追加して、新しいインデックスを取得し、続いて新しい文字列を取得します。
これは小文字でのみ機能することに注意してください (ただし、いつでも使用できますstring = string.lower()
)。英語以外のアルファベットを使用する場合は、調整する必要があります。
コードを国際的に機能させたい場合は、locale
モジュールを使用して、任意の言語を指定してローカルのアルファベットを取得できます。
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
現在、これは、現在のコンピューターが設定されているローカルのアルファベットを取得するだけです。の 2 番目の引数を編集することで、基になる言語を変更できると思いますlocale.setlocale
。
このstring.lowercase
属性は、指定された言語のすべての小文字を順番に返します。
locale.setlocale
これはスレッドセーフとは見なされず、プログラム全体に適用されることに注意してください。