LoginSignup
0
1

More than 3 years have passed since last update.

Pythonで、Rubyのto_sはどう書くのか

Last updated at Posted at 2020-07-30

Rubyを学習した後に、Pythonの勉強に入った方がいらっしゃると思います。そしてPythonの勉強中、「Rubyのあのメソッドって、Pythonではどう書くんだろう」となることがあると思います。今回は、そのto_s版です。

結論

Ruby => 文字列に変換したい値.to_s
Python => str(文字列に変換したい値)


# Rubyの場合
name = SampleUser
name.to_s
  # "SampleUser"

# Pythonの場合
name = SampleUser
str(name)
  # "SampleUser"

追記

@shiracamus さんコメントより引用(ありがとうございます!!!)

各オブジェクトは strメソッドや reprメソッドを持っています。
str関数(実体はstrクラス)はそれらのメソッドを適切に呼び出して文字列化し、さらに文字コード変換してくれます。
参考: https://docs.python.org/ja/3/library/stdtypes.html#str

>>> 123 .__str__()
'123'
>>> 3.14.__str__()
'3.14'
>>> None.__str__()
'None'

参考
https://www.javadrive.jp/python/function/index2.html

0
1
1

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
1