learner_99 learner_99 - 1 year ago 112
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'

clock = Clock('5:30')

Why does it print
instead of

Answer Source

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)
>>> print(type(time))
<class 'str'>
>>> print(repr(time))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download