\ t我的代码不起作用,也没有

时间:2017-04-13 13:55:00

标签: python-2.7

嘿我想知道为什么这在我的代码中不起作用, 我倾向于从其他论坛中相信,在语音标记中放置\ t和\ n应该可以修复结果:

zoo = ("Kangaroo","Leopard","Moose")
print("Tuple:", zoo, "\tLength:", len(zoo))
print(type( zoo))

bag = {'Red','Green','Blue'}
bag.add('Yellow')
print('\nSet:',bag,'\tLength' , len(bag))
print(type(bag))

print('\nIs Green In bag Set?:','Green' in bag)
print('Is orange in bag set?:', 'Orange' in bag)

box = {'Red','Purple','Yellow'}
print('\nSet:',box,'\t\tLength' , len(box))
print('Common to both sets:' , bag.intersection(box))

它只是说:

('Tuple:', ('Kangaroo', 'Leopard', 'Moose'), '\tLength:', 3)
<type 'tuple'>
('\nSet:', set(['Blue', 'Green', 'Yellow', 'Red']), '\tLength', 4)
<type 'set'>
('\nIs Green In bag Set?:', True)
('Is orange in bag set?:', False)
('\nSet:', set(['Purple', 'Yellow', 'Red']), '\t\tLength', 3)
('Common to both sets:', set(['Red', 'Yellow']))

3 个答案:

答案 0 :(得分:0)

print是python2.7中的一个命令,而不是一个函数,因此括号被解释为周围的元组,这就是打印的内容。正在显示控制字符(而不是它们的效果),因为您不是直接打印字符串,而是作为元组的一部分。

答案 1 :(得分:0)

你可以做到这一点而不需要改变太多。

zoo = ("Kangaroo","Leopard","Moose")
zlength = len(zoo)
print "Tuple: {}, \tLength: {}".format(zoo,zlength)
print type(zoo)

bag = {'Red','Green','Blue'}
bag.add('Yellow')
blength = len(bag)
print '\nSet: {}, \tLength: {}'.format(list(bag), blength)
print type(bag)

print '\nIs Green In bag Set?:','Green' in bag
print 'Is orange in bag set?:', 'Orange' in bag

box = {'Red','Purple','Yellow'}
bolength = len(box)
print '\nSet: {}, \tLength: {}'.format(list(box),bolength)
print 'Common to both sets:' , list(bag.intersection(box))

<强> OUPUT:

  

元组:(&#39;袋鼠&#39;,&#39; Leopard&#39;,&#39; Moose&#39;),长度:3

     

设置:[&#39; Blue&#39;,&#39; Green&#39;,&#39; Yellow&#39;,&#39; Red&#39;],长度:4

     

绿色袋装?:是

     

袋装橙色?:错误

     

设置:[&#39;紫色&#39;,&#39;红色&#39;黄色&#39;],长度:3

     

两套相同:[&#39;黄色&#39;,&#39;红色&#39;]

答案 2 :(得分:0)

在Python 2.7中,名称print被识别为print语句,而不是内置函数。您可以通过在模块顶部添加以下future语句来禁用该语句并使用print()函数:

from __future__ import print_function

因此,例如:

>>> zoo = ("Kangaroo","Leopard","Moose")
>>> print("Tuple:", zoo, "\tLength:", len(zoo))
('Tuple:', ('Kangaroo', 'Leopard', 'Moose'), '\tLength:', 3)
>>> from __future__ import print_function
>>> print("Tuple:", zoo, "\tLength:", len(zoo))
Tuple: ('Kangaroo', 'Leopard', 'Moose')         Length: 3
>>>