learner_99 learner_99 - 8 days ago 7
Python Question

Why Python is returning integer instead of string

class Clock(object):
def __init__(self, time):
self.time = time
def print_time(self):
time = '6:30'
print(self.time)

clock = Clock('5:30')
clock.print_time()


Why does it print
5:30
instead of
'5:30'
?

Answer

When you write a python program, strings need to be placed inside quotes so that the parser knows they are strings. So, you type

>>> time = 5:30
  File "<stdin>", line 1
    time = 5:30
            ^
SyntaxError: invalid syntax
>>>
>>> time = '5:30'
>>> 

But python doesn't really store the quotes themselves in the string. It creates an object of type str whose value is 5:30. When you print the string, it prints the value, not the quoted representation needed to get the python parser to work.

Python objects have two methods for displaying themselves. __str__ returns the expected human-readable string while __repr__ returns a programmer-friendly string that usually includes type information. For a string, it includes the quotes. If you really want the quotes for some reason, you can use repr

>>> time = '5:30'
>>> print(time)
5:30
>>> print(type(time))
<class 'str'>
>>> print(repr(time))
'5:30'
>>> 
Comments