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?

Python 3 エンジニア認定基礎試験 合格に向けて part7 (repr)

1
Posted at

なるほど、じゃあ「repr」の意味をゼロから説明するで 😄


repr とは?

  • Python の組み込み関数で、オブジェクトを「開発者向けにわかりやすい文字列」に変換するもの
  • 「このオブジェクトをコードとして書くならこうなる」ってイメージ
  • 逆に str()ユーザー向けに見やすい文字列を返す

s = "Hello, world."
print(str(s))   # ユーザー向け → Hello, world.
print(repr(s))  # 開発者向け → 'Hello, world.'
  • str(s) はそのまま表示
  • repr(s)' で囲まれたり、エスケープ文字も含まれて、文字列としての形がはっきりわかる

もう少し具体的に言うと、repr()デバッグ用 に使うことが多いんや。
文字列だけやなくて、数値やリストでも同じように「Python コードとして書いた形」を返す。

x = [1, 2, 3]
print(str(x))   # [1, 2, 3]
print(repr(x))  # [1, 2, 3]  ← 見た目同じでも、中身はコードとして解釈できる形

1️⃣ 見た目だけじゃわからないときに役立つ

s = "Hello\nWorld"
print(str(s))
# 出力:
# Hello
# World

print(repr(s))
# 出力:
# 'Hello\nWorld'
  • str() は「人が読む用」だから改行がそのまま画面に出る
  • repr() は「文字列の中身を正確に表す」から \n が見える
    デバッグするときに「本当は改行が入ってるのか?」がすぐわかる

2️⃣ 開発者向け・再利用しやすい

  • repr() はそのまま Python コードとして評価できる形 になることが多い
s = 'Hello'
r = repr(s)  # r = "'Hello'"
eval(r)      # -> 'Hello'
  • だから「オブジェクトを保存して後で復元」するときに便利

まとめると、repr() の利点は:

  1. 中身を正確に確認できる(改行、タブ、特殊文字も見える)
  2. コードとして使える形 なので、デバッグや保存・復元に便利
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?