【问题标题】:Why Python is returning integer instead of string [closed]为什么 Python 返回整数而不是字符串 [关闭]
【发布时间】:2017-04-05 03:12:54
【问题描述】:
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()

为什么打印5:30 而不是'5:30'

【问题讨论】:

  • 5:30 不是整数。
  • 引号不是字符串的一部分,5:30 不是整数

标签: python string class object integer


【解决方案1】:

在编写 Python 程序时,字符串需要放在引号内,以便解析器知道它们是字符串。所以,你输入

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

但是 python 并没有真正将引号本身存储在字符串中。它创建一个类型为str 的对象,其值为5:30。当您打印字符串时,它会打印值,而不是让 python 解析器工作所需的引用表示。

Python 对象有两种显示自身的方法。 __str__ 返回预期的人类可读字符串,而__repr__ 返回通常包含类型信息的程序员友好字符串。对于字符串,它包括引号。如果您出于某种原因确实想要引号,可以使用repr

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

【讨论】:

    【解决方案2】:

    ""'' 只是分隔字符串,它们不是字符串的一部分,因此不会被打印。 程序在此处正确打印字符串。 (5:30 无论如何都不是整数)

    PS:我不知道print_time 中的time = '6:30' 是否应该更改Clock 中的时间属性,但如果是,它应该是self.time = '6:30'。当前指令没有任何作用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-08
      • 1970-01-01
      • 1970-01-01
      • 2016-09-28
      相关资源
      最近更新 更多