1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Codewars 6 kyu Replace With Alphabet Position

1
Posted at

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 } という辞書ができる。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?