str() vs repr() in Python

您所在的位置:网站首页 reprpython str() vs repr() in Python

str() vs repr() in Python

2024-07-15 11:54:33| 来源: 网络整理| 查看: 265

In Python, the str() and repr() functions are used to obtain string representations of objects. While they may seem similar at first glance, there are some differences in how they behave. Both of the functions can be helpful in debugging or printing useful information about the object.

Python str()

In the given example, we are using the str() function on a string and floating values in Python.

Python3

s = 'Hello, Geeks.' print (str(s)) print (str(2.0/11.0))

Output:

Hello, Geeks. 0.181818181818 Python repr()

In the given example, we are using the repr() function on a string and floating values in Python.

Python3

s = 'Hello, Geeks.' print (repr(s)) print (repr(2.0/11.0))

Output:

'Hello, Geeks.' 0.18181818181818182 str() vs repr() in Python Examples

From the above output, we can see if we print a string using the repr() function then it prints with a pair of quotes and if we calculate a value we get a more precise value than the str() function.

Python __str__() and __repr__() with  a Built-In Class

In this example, we are creating a DateTime object of the current time and we are printing it into two different formats.

str() displays today’s date in a way that the user can understand the date and time. repr() prints an “official” representation of a date-time object (means using the “official” string representation we can reconstruct the object).

Python3

import datetime today = datetime.datetime.now()   # Prints readable format for date-time object print(str(today))   # prints the official format of date-time object print(repr(today))

Output :

2016-02-22 19:32:04.078030 datetime.datetime(2016, 2, 22, 19, 32, 4, 78030) How to make them work for our own defined classes? 

A user-defined class should also have a __repr__() if we need detailed information for debugging. And if we think it would be useful to have a string version for users, we create a __str__() function. In this example, We have created a class Complex which has two instance variables real and imag. We are creating custom __repr__() and __str__() methods in the class.

Python3

# Python program to demonstrate writing of __repr__ and # __str__ for user defined classes   # A user defined class to represent Complex numbers class Complex:       # Constructor     def __init__(self, real, imag):     self.real = real     self.imag = imag       # For call to repr(). Prints object's information     def __repr__(self):     return 'Rational(%s, %s)' % (self.real, self.imag)          # For call to str(). Prints readable form     def __str__(self):     return '%s + i%s' % (self.real, self.imag)        # Driver program to test above t = Complex(10, 20)   # Same as "print t" print (str(t)) print (repr(t))

Output :

10 + i20 Rational(10, 20) Difference between Python str() and Python repr()

Points

str()

repr()

Return Value

Returns a human-readable string representation of the object

Returns an unambiguous string representation of the object

Usage

Used for creating user-friendly output and for displaying the object as a string

Used for debugging and development purposes to get the complete information of an object

Examples

str(123) returns ‘123’

repr(123) returns ‘123’

 

str(‘hello’) returns ‘hello’

repr(‘hello’) returns “‘hello'”

 

str([1, 2, 3]) returns ‘[1, 2, 3]’

repr([1, 2, 3]) returns ‘[1, 2, 3]’

 

str({‘name’: ‘John’, ‘age’: 30}) returns “{‘name’: ‘John’, ‘age’: 30}”

repr({‘name’: ‘John’, ‘age’: 30}) returns “{‘name’: ‘John’, ‘age’: 30}”

https://media.geeksforgeeks.org/auth/avatar.png GeeksforGeeks Improve Next Article f-strings in Python Please Login to comment...


【本文地址】

公司简介

联系我们

今日新闻


点击排行

实验室常用的仪器、试剂和
说到实验室常用到的东西,主要就分为仪器、试剂和耗
不用再找了,全球10大实验
01、赛默飞世尔科技(热电)Thermo Fisher Scientif
三代水柜的量产巅峰T-72坦
作者:寞寒最近,西边闹腾挺大,本来小寞以为忙完这
通风柜跟实验室通风系统有
说到通风柜跟实验室通风,不少人都纠结二者到底是不
集消毒杀菌、烘干收纳为一
厨房是家里细菌较多的地方,潮湿的环境、没有完全密
实验室设备之全钢实验台如
全钢实验台是实验室家具中较为重要的家具之一,很多

推荐新闻


图片新闻

实验室药品柜的特性有哪些
实验室药品柜是实验室家具的重要组成部分之一,主要
小学科学实验中有哪些教学
计算机 计算器 一般 打孔器 打气筒 仪器车 显微镜
实验室各种仪器原理动图讲
1.紫外分光光谱UV分析原理:吸收紫外光能量,引起分
高中化学常见仪器及实验装
1、可加热仪器:2、计量仪器:(1)仪器A的名称:量
微生物操作主要设备和器具
今天盘点一下微生物操作主要设备和器具,别嫌我啰嗦
浅谈通风柜使用基本常识
 众所周知,通风柜功能中最主要的就是排气功能。在

专题文章

    CopyRight 2018-2019 实验室设备网 版权所有 win10的实时保护怎么永久关闭