6 kyu Replace With Alphabet Position
Task
In this kata you are required to, given a string, replace every letter with its position in the alphabet.
If anything in the text isn't a letter, ignore it and don't return it.
Verbalization
Dictionaryでアルファベットと数字を対応させる(例 a:1, b:2…)
文字列からアルファベットだけfor i in でとりだす(スペースやカンマなどはとりださない)
1.で対応させた数字を返す
Code
def alphabet_position(text):
alpha_dict = {chr(i+96):i for i in range(1,27)}
result = []
for char in text.lower():
if char in alpha_dict:
result.append(str(alpha_dict[char]))
return " ".join(result)
Reference
*アルファベットと数字の対応表(Dictionary)をつくる
alpha_dict = {chr(i + 96): i for i in range(1, 27)}
chr(97) が 'a'
chr(98) が 'b'
…というASCIIコードの仕組みを使って a=1〜z=26 を自動で作っている。
{ 'a':1, 'b':2, ..., 'z':26 } という辞書ができる。