Python学习n天:元组的加入与字符串的初现
元组(tuple)
与列表一样,它也是一个容器型数据类型,但是是不可变的容器。
元组与列表操作相似,但是又有些不同,元组只能进行两个写操作index()
与count()
,并不能进行列表的其他操作。
"""
example02 - 元组(Tuple) ---> 不可变的容器
Author:悾格
Date: 2021/7/27
"""
# 定义一个元组
# 元组中只有一个元素时,千万不要忘记打逗号,不然电脑会认为是字符串
# fruits1 = ('apple',)
fruits1 = ('apple', 'banana', 'grape')
print(type(fruits1))
# 重复运算
print(fruits1 * 3)
# 成员运算
print('apple' in fruits1)
print('grape' not in fruits1)
# 合并运算
fruits2 = ('pitaya', 'litchi')
fruits3 = fruits1 + fruits2
print(fruits3)
# 索引和切片 assignment:赋值
# 索引只能进行读操作
print(fruits3[4], fruits3[-1])
print(fruits3[1:4])
print(fruits3[1:4:2])
# 反向切片
print(fruits3[::-1])
# del fruits3[0] 'tuple' object doesn't support item deletion
# 元组对于写的操作只有index()和 count()
print(fruits3.index('apple'))
print(fruits3.count('apple'))
打包和解包
"""
example03 - 元组的应用
unpack:解包,把一个元组拆成多个元素
Author:悾格
Date: 2021/7/27
"""
*a, b, c = 5, 10, 15, 20, 25
print(a)
print(b)
print(c)
print('-' * 20)
a, *b, c = 5, 10, 15, 20, 25
print(a)
print(b)
print(c)
print('-' * 20)
a, b, *c = 5, 10, 15, 20, 25
print(a)
print(b)
print(c)
字符串
所谓字符串,就是由零个或多个字符组成的有限序列。
"""
example04 - 字符串
Author:悾格
Date: 2021/7/27
"""
# 转义字符
# \b:退格
a = '\'hello,\tworld\b\''
b = "\"hello,\nworld\""
c = '''
hello,
world!
'''
print(a)
print(b)
print(c)
# 原始字符串(每个字符都是它原始的含义,没有转义字符)
d = r'c:\User\Administrator\abc\hello.py'
print(d)
# 带占位符的字符串(格式化字符串)
e = f'文件路径:{d}'
print(e)
s1 = '\141\142\143\x61\x62\x63'
print(s1)
# ASCII ---> GB2312 ---> GBK ---> Unicode(UTF-8)(所有主流字符)