字符串追加以及为什么不同变量的打印不返回?

时间:2018-05-27 17:12:14

标签: python string list

我正在尝试将一个项目添加到我的列表中:' pepperoni '使用append

pizza_vege=['tomato sauce','mushrooms','pepper','cheese','garlic powder']
print(pizza_vege)
pizza_peper=pizza_vege.append('peperoni')
print(pizza_peper) #The result here should show the list of pizza_vege and add 'pepperoni to it'

显示的结果是:

['tomato sauce', 'mushrooms', 'pepper', 'cheese', 'garlic powder']
None

我不明白为什么'print'会在输出中返回'None'。是不是应该加入两个序列??

谢谢大家!

2 个答案:

答案 0 :(得分:0)

将您的代码更改为

pizza_vege=['tomato sauce','mushrooms','pepper','cheese','garlic powder']
print(pizza_vege)
pizza_vege.append('peperoni')
print(pizza_vege)

哪个收益

['tomato sauce', 'mushrooms', 'pepper', 'cheese', 'garlic powder']
['tomato sauce', 'mushrooms', 'pepper', 'cheese', 'garlic powder', 'peperoni']

答案 1 :(得分:0)

在上面,.append将项目添加到原始列表并返回None。相反,如果您想要pizza_vegepizza_peper两个不同的列表,那么您可以尝试:

pizza_vege=['tomato sauce','mushrooms','pepper','cheese','garlic powder']
pizza_peper = pizza_vege + ['peperoni']

print(pizza_vege)
print(pizza_peper) #The result here should show the list of pizza_vege and add 'pepperoni to it'

结果:

['tomato sauce', 'mushrooms', 'pepper', 'cheese', 'garlic powder']
['tomato sauce', 'mushrooms', 'pepper', 'cheese', 'garlic powder', 'peperoni']