LoginSignup
2
4

More than 1 year has passed since last update.

#python の str と repr の違いって何なの? ( str は非公式のオブジェクト表現 / repr は公式の表現 )

Last updated at Posted at 2019-05-07

ref

str vs. repr

str vs. repr
According to the official Python documentation, repr is a built-in function used to compute the "official" string reputation of an object, while str is a built-in function that computes the "informal" string representations of an object. So both repr and str are used to represent objects, but in different ways. The best way to understand the difference between these two functions is to see them in action:

Google日本語訳

str vs. repr
公式のPythonドキュメントによると、__repr__はオブジェクトの「公式の」文字列レピュテーションを計算するために使用される組み込み関数ですが、__str__はオブジェクトの「非公式の」文字列表現を計算する組み込み関数です。そのため、__repr__と__str__はどちらもオブジェクトを表すために使用されますが、その使用方法は異なります。これら2つの機能の違いを理解するための最良の方法は、それらが実際に動作していることを確認することです。

str は非公式で repr は公式らしいです。

まだよくわかりませんが。

文字列を書くときってクォーテーションで囲いますよね

>>> "some"
'some'

そのまま書いたら未定義ですよって怒られます

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'some' is not defined

文字列はevalできないけど

>>> eval("some")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'some' is not defined

文字列の repr は eval できるわけですよ

>>> eval(repr("some"))
'some'

文字列は文字列で

>>> "some"
'some'
>>> str("some")
'some'

repr はオブジェクトの「フォーマルな表現」みたいですね?

>>> repr("some")
"'some'"

つまり repr で得られる文字列は eval できるわけです

>>> eval("'some'")
'some'

こんな理解で合ってますでしょうか?

それではごきげんよう。

Original by Github issue

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

Twitter

2
4
4

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
2
4