【问题标题】:Print command writing in one line [duplicate]打印命令写入一行[重复]
【发布时间】:2020-06-05 23:13:31
【问题描述】:

我正在学习 Python,对打印命令有疑问。

为什么在以下情况下打印命令的代码在一行中工作:

text = "The vegetables are in the fridge."
print(text.replace("vegetables", "fruits"))

但是当我这样写时,我没有得到任何结果?

numbers = [12, 34, 23, 88, 1, 65]
fruits = ["apple", "pear", "orange", "grapes", "mango"]
print(fruits.extend(numbers))

正确的方法如下:

numbers = [12, 34, 23, 88, 1, 65]
fruits = ["apple", "pear", "orange", "grapes", "mango"]
fruits.extend(numbers)
print(fruits)

我的意思是,如果逻辑如下,第一个函数起作用,然后是第二个,那么为什么在第一个函数中它才起作用?

希望我能解释一下。

先谢谢了,

莉莉丝

【问题讨论】:

  • 因为replace返回的是替换后的字符串,而extend将指定的列表元素添加到当前列表的末尾而不返回。

标签: python python-3.x printing command


【解决方案1】:

.extend(...) 返回None。任何就地改变对象的方法都会返回None

.replace(...) 返回一个带有替换值的新字符串。

但是你可以试试这个单线。

print(fruits.extend(numbers) or fruits)
#['apple', 'pear', 'orange', 'grapes', 'mango', 12, 34, 23, 88, 1, 65]

Docs say :

【讨论】:

    【解决方案2】:

    Python 字符串是不可变 对象,这意味着对其执行的方法会返回新字符串。

    另一方面,列表是可变的,这意味着您可以更改它们:将项目添加到列表中,更改列表中的特定项目等。这些更改是就地完成的:更改相同的列表。

    通常,就地完成的方法没有返回值。 fruits.extend(numbers) 没有返回值,因为它更改了 fruits

    如果您之后需要使用fruits,您将其分成两行的解决方案很好。如果没有,您可以创建一个新列表并将其打印如下:

    numbers = [12, 34, 23, 88, 1, 65]
    fruits = ["apple", "pear", "orange", "grapes", "mango"]
    print(fruits + numbers)
    

    【讨论】:

      【解决方案3】:
      >>>fruits.extend(numbers)
      None
      

      这会改变水果 但是新值没有返回

      【讨论】:

        【解决方案4】:

        这是你认为它在做什么:

        def extfruits(l1, l2):
            l3 = l1 + l2
            return l3
        print(extfruits(fruits, numbers))
        

        实际上,它是在打印方法,这只是在原地改变水果的价值。所以,你得到 None。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2012-12-18
          • 2012-03-24
          • 1970-01-01
          • 2012-07-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多