0
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?

#0134(2025/05/14)Python 組み込み関数 `chr()` と `ord()`

Posted at

Python 組み込み関数 chr()ord()

🔡 chr():整数(Unicodeコード)→ 文字

  • 構文chr(i)

  • 引数:整数(Unicodeコードポイント)

  • 戻り値:そのコードに対応する文字(str型)

  • 範囲:0〜1,114,111(0x10FFFF)

  • chr(97)   # 'a'
    chr(65)   # 'A'
    chr(124)  # '|'
    

🔢 ord():文字 → 整数(Unicodeコード)

  • 構文ord(c)

  • 引数:1文字の文字列(str型)

  • 戻り値:その文字のUnicodeコードポイント(int型)

  • ord('a')  # 97
    ord('A')  # 65
    ord('|')  # 124
    ord('') # 12354(U+3042)
    

🧠 ASCII との関係

  • ASCII は Unicode の最初の 128 文字(0〜127)を含む。

  • 例えば:

    • ord('a') は ASCII コード 97
    • chr(97) は 'a'

🔄 他のエンコーディング(UTF-8やShift_JISなど)について

  • chr()ord()Unicode専用 であり、UTF-8やShift_JISなどのバイトエンコーディングとは直接関係ありません
  • 他のエンコーディングを扱いたい場合は、次のように encode() / decode() を使用します:

🔸 文字列 → バイト列

''.encode('utf-8')       # b'\xe3\x81\x82'
''.encode('shift_jis')   # b'\x82\xa0'

🔸 バイト列 → 文字列

b'\xe3\x81\x82'.decode('utf-8')      # 'あ'
b'\x82\xa0'.decode('shift_jis')      # 'あ'

デフォルトエンコーディングの確認

import sys
print(sys.getdefaultencoding())  # 通常は 'utf-8'
  • Python 3 では str 型は常に Unicode を前提としています。

🎯 よくある用途

1. アルファベット列を生成

for i in range(26):
    print(chr(ord('a') + i), end=' ')  # a b c ... z

2. シーザー暗号(Caesar Cipher)などの暗号処理

  • アルファベット → 数値 → シフト → 文字に戻す、という処理で使う

3. 英字ラベルの自動生成

label = chr(ord('A') + 3)  # 'D'

✅ まとめ表

関数 説明
ord() 文字 → Unicode(int) ord('a') → 97
chr() Unicode(int) → 文字 chr(97) → 'a'

Pythonで文字と数値を相互に変換する際には、chr()ord()の活用が非常に便利です。バイト列や他の文字コードを扱いたい場合は encode() / decode() を使い分けましょう。

0
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
0
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?