LoginSignup
23
23

More than 5 years have passed since last update.

python3: repr()、str()、eval()とは

Last updated at Posted at 2016-02-02

学校の宿題をしていたらQuestion7でこんな問題に:

Write a one-line program that prints itself, using only the following features of the Python language:

  • Number literals
  • Assignment statements
  • String literals that can be expressed using single or double quotes
  • The arithmetic operators +, -, *, and /
  • The built-in print function
  • The built-in eval function, which evaluates a string as a Python expression
  • The built-in repr function, which returns an expression that evaluates to its argument
  • You can concatenate two strings by adding them together with + and repeat a string by multipying it by an integer. - Semicolons can be used to separate multiple statements on the same line. E.g.,
>> c='c';print('a');print('b' + c * 2)
a
bcc

Question7自体はまた別の記事で書くとして今回はrepr()についてのみ焦点を置いて考えてみることにする。

repr()とは

もともとはこんな感じobject.__repr__(self)str()と比較しながらだとより分かりやすいかもしれない。

pythonのオフィシャルを参照に見てみると:

Called by the repr() built-in function to compute the “official” string representation of an object.

どうやら__repr__がofficial string representaionで__str__がinformal string representationっぽいですね。

>>> y = 'a string'
>>> repr(y)
"'a string'"
>>> str(y)
'a string'
>>> a = 'a'
>>> eval(str(a))
'a'
>>> eval(repr(a))
'a'

また他の記事では:

The print statement and str() built-in function uses __str__ to display the string representation of the object while the repr() built-in function uses __repr__ to display the object.

>>> import datetime
>>> today = datetime.datetime.now()
>>> str(today)
'2016-01-30 01:56:09.287104'
>>> repr(today)
'datetime.datetime(2016, 1, 30, 1, 56, 9, 287104)'

str()を使うとユーザーに分かりやすいように時間表示してくれる。見ただけで直感的に何時か分かる。

repr()でも返ってきた値はストリングだが(ここでいう)officialとして表示されている。officialというのは簡単にいえばその値を再利用できるかどうか。

>>> eval(repr(today))
datetime.datetime(2016, 1, 30, 1, 56, 9, 287104)
>>> eval(str(today))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1
    2016-01-30 01:56:09.287104
          ^
SyntaxError: invalid token

eval()はストリングを受け取ってdatetimeのオブジェクトへと変えてくれる。identifier的な。

repr()周辺の理解をするために

手始めとしてクォーテーションマークのことも少しくらいは知っておいたほうがいいかと思います:

やってくれること

簡単にいえば受け取った引数にシングルクォーテーションマークを付けて返してくれる。

>>> x = 1
>>> repr(x)
'1'

ちなみに

>>> x = 'a'
>>> eval(repr(x)) == x
True

その他、補足

strの特徴をうまく使った関数を見つけたのでメモがてら。

strはリストと似たような扱い方をすることができる。

str with for loop

strを引数として受け取りそこにfor loopをかけて一つ一つの単語を抜き出すことができる。

def shout(string):
    for character in string:
        print("Gimme a " + character)
        print("'" + character + "'")

shout("Lose")

str with len()

listと同様strにもlen()かけて長さを図れる。ということはa番目の文字=str[a]をちょっといじくると単語の真ん中の文字 = その単語の長さ//2番目の単語 = str[len(str) // 2]になる。

def middle(string):
    print("The middle character is:", string[len(string) // 2])

middle("abcdefg")
middle("The Python Programming Language")
middle("Atlanta")

output:

Gimme a L
'L'
Gimme a o
'o'
Gimme a s
's'
Gimme a e
'e'
The middle character is: d
The middle character is: r
The middle character is: a

参考にしたリンク

23
23
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
23
23