Python基础---Task04:字符串与序列
sequence序列
序列对象包括:string, list, tuple, set, dict
打包与解包
n个(与序列所含元素个数一致)的变量 = 任意系列解包操作的等号右侧可以是任何序列。变量不足时可用 _ 占位
t = 12345, 54321, 'hello!'
# 数据打包进元组t
x, _, y = t
# 序列解包,按序赋值, _占位
比较大小
- 执行字典式顺序比较,字典式顺序是使用 Unicode 码位序号对单个字符排序
(1, 2, 3) < (1, 2, 4)
[1, 2, 3] < [1, 2, 4]
‘ABC’ < ‘C’ < ‘Pascal’ < ‘Python’
(1, 2, 3, 4) < (1, 2, 4)
(1, 2) < (1, 2, -1)
(1, 2, 3) == (1.0, 2.0, 3.0)
(1, 2, (‘aa’, ‘ab’)) < (1, 2, (‘abc’, ‘a’), 4)
- 排序顺序:
每个元素有前后标,顺序从0,逆序从-1开始
P | y | t | h | o | n |
---|
0_______1_______2_______3_______4________5_______6
-6______-5_______-4______-3_______-2_______-1
查找元素
所有序列均可以切片
字符串
创建字符串
- ’ ’ 和 " " 只能单行使用行使用, ‘’’ ‘’’ 和 “”" “”" 用于定义初始化时表示多行字符串,否则中表示多行注释
- 当字符串中包含 ’ ’ 和 " " 时,在每个引号前加 \ 或使用三引号即可
single = 'say a \'word\''
#\用来转义成字符
double1 = '''live a\
'real' life'''
double2 = '''live a
'real' life'''
#每行尾加 \,表示输出中不包含\n
'''这是
多行注释'''
address = r'E:/name/python'
#r表示不转义
print(address)
>> E:/name/python
single + double1
>> "say a 'word'live a'real' life"
字符串方法: str.xxx(*args)
print(double1,'\n',double1.capitalize())
# 返回首字母大写副本
>> live a 'real' life
Live a 'real' life
end = 'i'
print(double1.endswith(end))
#查找字符串是否以end结尾,是返回True
>> False
url = 'http://www.python.org'
url.startswith('http:')
>> True
格式化
str . format ( ) 中,str内花括号 {} 括起来部分格式化,花括号之外的内容被视为字面文本,会不加修改地复制到输出中。若要输出{} 则用{{}}
print('{} is a fun'.format(lambda x: range(10)))
>> <function <lambda> at 0x000001B833A09378> is a fun
print('{{key:value}},{},{},{} are all sequences'.format(
'[elem,...]','(elem,)','\'string\''))
>> {key:value},[elem,...],(elem,),'string' are all sequences
检查格式
date1 = '11/27/2012'
date2 = 'Oct 24,2019'
import re
if re.match(r'\d+/\d+/\d+',date1):
print('date1 correct')
if re.match(r'\d+ \d+,\d+',date2):
print('date2 correct')
else:
print('incorrect')
>> date1 correct
incorrect
反思
细节方面多看官方文档,实例方面看网课效果较好。接下来就是较复杂的函数实现了,加深pythoncookbook难度。
参考链接:
Python CooKbook
https://python3-cookbook.readthedocs.io/zh_CN/latest/index.html
https://docs.python.org/zh-cn/3/tutorial/datastructures.html#tuples-and-sequences
https://www.icourse163.org/learn/BIT-268001?tid=1207014257#/learn/announce
5 days