1. 字符串
字符串通过单引号 ' ' 或双引号 " " 来标识。字符串可以看成字符的序列,具有索引和切片操作。字符串不支持修改
字符串创建、索引和切片
# 创建字符串
s = 'iloveyou'
# 字符串索引和切片
s[0] # 提取第1个字符
s[0:2] # 正向截取字符串0~2(不包含索引2)
s[0:] # 正向截取字符串0~末尾
s[0:-2] # 正向截取字符串0~倒数第二个索引(不包含倒数第二个索引值)
s[::2] # 正向截取字符串所有字符,增量为2
s[::-2] # 反向截取字符串所有字符,增量为2
字符串的 split 和 join 方法
# join方法,以字符串列表为参数,返回拼接字符串,在串之间插入调用join方法的字符串
' '.join(['Hi', 'Maria']) # 输出:Hi Maria
# split方法,默认按空格为分隔符拆分字符串为子字符串列表
'Hi Maria'.split() # 输出:['Hi', 'Maria']
去除多余空白符
str_name.strip(), str_name.lstrip(), str_name.rstrip()
t = ' sex man ' # 字符串首位末尾包含空白字符
a = t.strip()
b = t.lstrip()
c = t.rstrip()
print([a, b, c]) # ['sex man', 'sex man ', ' sex man']
2. 字典
字典可以简单理解为“键值对”,用“键”存储、索引“值”。键通常是字符串或数字,也可以是其他任意不可变类型。
- 用已存在的键存储值,旧值会被取代;用不存在的键提取值,会报错
- list(dict_name)返回字典键的列表
- in关键字检查键是否在字典中
## 字典创建
test_dict = {} # 创建空字典
test_dict = {'Jack':37, 'Leo':28, 'Jane':14, 'Jane':18} # 创建字典
test_dict = dict([('Jack',37), ('Leo',28), ('Jane',14), ('Jane',18)]) # dict()函数构建字典
test_dict = dict(Jack=37, Leo=28, Jane=18) # 适用关键字简单,此方式不支持关键字重复
# 用键索引值
test_dict['Jane'] # 输出18
keys_name = list(test_dict) # 输出['Jack', 'Leo', 'Jane']
print('Jack' in test_dict) # 输出True
print('Jack' not in test_dict) # 输出False