通过加法运算符将列表连接起来,加法运算符还可将字符串连接起来,但是,不能将列表和字符串连接。
>>> [1,2,3]+[4,5,6]
[1, 2, 3, 4, 5, 6]
>>> 'hello,'+'world!'
'hello,world!'
>>> [1,2,3]+'hello'
>>> [1,2,3]+'hello'
Traceback (most recent call last):
File "" , line 1, in
[1,2,3]+'hello'
TypeError: can only concatenate list (not "str") to list
>>>
用数字x乘以一个列表生成一个新列表,即原来的列表被重复x次(字符串也这样)。
>>> 'python'*3
pythonpythonpython'
>>>[31]*3
[31, 31, 31]
>>>
空列表 [ ] 表示什么都没有。
初始化 None 表示“没有内容”,但是需要创建一个占用多个元素的空间。
>>> result=[None]*4
>>> result
[None, None, None, None]
>>>
盒子例子
打印一个由字符组成的盒子,盒子在屏幕上居中且根据用户输入的句子自动调整大小。
盒子1:
#以正确宽度在居中的盒子内打印句子
sentence=raw_input('sentence:')
screen_width = 80
text_width = len(sentence)
box_width = text_width + 6
left_margin = (screen_width - box_width)//2
print
print ' '*left_margin+ '+' + '_' * (box_width-2) + '+'
print ' '*left_margin+ '|' +' '* (box_width-2) + '|'
print ' '*left_margin+ '|' + (box_width-text_width-2)//2*' '+sentence +(box_width-text_width-2)//2*' '+ '|'
print ' '*left_margin+ '|' +' '* (box_width-2) + '|'
print ' '*left_margin+ '+' + '_' * (box_width-2) + '+'
print
结果为:
>>> ================================ RESTART ================================
>>>
sentence:Where are you ?
+___________________+
| |
| Where are you ? |
| |
+___________________+
>>>
>>> ================================ RESTART ================================
>>>
sentence:do you know you are a bad man?
+__________________________________+
| |
| do you know you are a bad man? |
| |
+__________________________________+
>>>
盒子2:
#以正确宽度在居中的盒子内打印句子
sentence=raw_input('sentence:')
screen_width = 80
text_width = len(sentence)
box_width = text_width + 6
left_margin = (screen_width - box_width)//2
print
print ' '*left_margin+ '+' + '_' * (box_width-2) + '+'
print ' '*(left_margin+(box_width-text_width-2)//2)+ '|' +' '* text_width + '|'
print ' '*(left_margin+(box_width-text_width-2)//2)+ '|' +sentence + '|'
print ' '*(left_margin+(box_width-text_width-2)//2)+ '|' +' '* text_width + '|'
print ' '*left_margin+ '+' + '_' * (box_width-2) + '+'
print
结果为:
>>> ================================ RESTART ================================
>>>
sentence:Where are you ?
+___________________+
| |
|Where are you ?|
| |
+___________________+
>>> ================================ RESTART ================================
>>>
sentence:Do you know you are a bad man?
+__________________________________+
| |
|Do you know you are a bad man?|
| |
+__________________________________+
>>>