python 序列

2019-09-24  本文已影响0人  zenos876

1.索引

# 直接使用编号访问各个元素
greeting = 'Hello'
print(greeting[0])

# 访问最后一个元素
print(greeting[-1])

# 可直接对序列进行索引操作
print('Hello'[0])

# 对函数返回的序列进行索引操作
name = input("请输入你的名字:")[0]
print(name)
========================1=========================
H
o
H
请输入你的名字:zenos
z

2.切片

# 简单切片  包含开始,不包含结尾
tag = '<a href="http://www.python.org">Python web site</a>'
print(tag[9:30])
print(tag[32:-4])

# 正向前一位必须比后一位大
numbers = [1,2,3,4,5,6,7,8,9,10]
print(numbers[7:10])
print(numbers[-3:0])

# 切片到末尾
print(numbers[0:])

# 切片从开头开始
print(numbers[:2])

# 复制整个序列
print(numbers[:])

# 正向步长
print(numbers[1:7:2])

# 反向步长 后一位必须比前一位大
print(numbers[8:3:-1])
========================2=========================
http://www.python.org
Python web site
[8, 9, 10]
[]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[2, 4, 6]
[9, 8, 7, 6, 5]

3.序列相加

# 同类型序列相加等于拼接
print([1,2,3]+[4,5,6])
print('hello' + 'world')

# 不同类型之间不可以进行相加
# print([1,2,3]+'hello')
========================3=========================
[1, 2, 3, 4, 5, 6]
helloworld

4.序列相乘(重复序列x次来创建新序列)

print('python'*5)
print([None]*5)
========================4=========================
pythonpythonpythonpythonpython
[None, None, None, None, None]

5.简单的例子

sentence = input("Setence:")
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 + '|  ' + ' ' * text_width + '  |')
print(' ' * left_margin + '|  ' + sentence + '  |')
print(' ' * left_margin + '|  ' + ' ' * text_width + '  |')
print(' ' * left_margin + '+' + '-' * (box_width - 2) + '+')
========================5=========================
Setence:hello world

                               +---------------+
                               |               |
                               |  hello world  |
                               |               |
                               +---------------+

6.成员资格 检查对象是否是序列的成员

permission = 'wx'
print('w' in permission)
========================6=========================
True
上一篇下一篇

猜你喜欢

热点阅读