接上文
四、变量
4.2 f-string (格式化字符串)
格式化字符串以 $f$ 开头,字符串中的表达式用 {} 包起来
x = 1
print(f'这个结果是{x+1}') #这个结果是2
a = 110
print(f"我的电话是{a}") #我的电话是110
4.3 字符串常见API
API:API指一组预定义的函数,协议或工具。简单来说,API就是别人已经帮你写好的函数,你可以直接调用这个函数。
例子:
1. str.lower(): 将字符串转换为小写
text = "Hello, World!"
print(text.lower()) # hello, world!
2. str.upper(): 将字符串转换为大写
text = "Hello, World!"
print(text.upper()) # HELLO, WORLD!
3. str.strip(): 移除字符串两端的空白字符,lstrip()去掉左边空白字符,rstrip()去掉右边空白字符
text = " Hello, World! "
print(text.strip()) # Hello, World!#
print(text.lstrip()) # Hello, World! #
print(text.rstrip()) # Hello, World!#
4. str.split(): 将字符串拆分为列表 (默认以空格拆分字符串,可添加参数以其他符号做分隔符)由于拆分后的结果是列表,则可以通过索引的方式继续拆分。
text = "Hello World!"
print(text.split()) # ['Hello', 'World!']
text = "Hello,World!"
print(text.split(',')) # ['Hello', 'World!']
text = "hello world"
re = text.split() # ['hello', 'world']
print(re[0].split('e')) # ['h', 'llo']
print(text.split()[0].split('e')) # ['h', 'llo']
5. str.join(): 将列表中的字符串连接为一个字符串
words = ['Hello', 'World']
print(" ".join(words)) # Hello World
words = ['apple', 'banana', 'cherry']
print(", ".join(words)) # apple, banana, cherry
6. str.replace(): 替换字符串中的子字符串 示例中将World换为Python
可以结合split()使用,例如要求你将字符串中的“?”,“!”,“。”,“ ”等作为分隔符将字符串分割成单词,可以先将“?”,“!”,“。”replace()成“ ”,再将“ ”split()得到结果。
text = "Hello, World!"
print(text.replace("World", "Python")) # Hello, Python!
text = "Hello?World!hello。world"
re_1 = text.replace("?", " ")
re_2 = re_1.replace("!", " ")
re_3 = re_2.replace("。", " ")
print(re_3.split()) # ['Hello', 'World', 'hello', 'world']
7. str.find(): 查找子字符串,返回第一次出现的位置
text = "Hello, World!"
print(text.find("World")) # 7
print(text.find("Python")) # -1(如果未找到则返回 -1)
8. str.startswith(): 检查字符串是否以指定子字符串开头
text = "Hello, World!"
print(text.startswith("Hello")) # True
print(text.startswith("World")) # False
9. str.endswith(): 检查字符串是否以指定子字符串结尾
text = "Hello, World!"
print(text.endswith("World!")) # True
print(text.endswith("Hello")) # False
10. str.isdigit(): 检查字符串是否只包含数字字符
text1 = "12345"
text2 = "12345abc"
print(text1.isdigit()) # True
print(text2.isdigit()) # False
11. str.isalpha(): 检查字符串是否只包含字母字符
text1 = "Hello"
text2 = "Hello123"
print(text1.isalpha()) # True
print(text2.isalpha()) # False
12. str.isalnum(): 检查字符串是否只包含字母和数字字符
text1 = "Hello123"
text2 = "Hello 123"
print(text1.isalnum()) # True
print(text2.isalnum()) # False
13. str.title(): 将字符串中的每个单词的首字母转换为大写
text = "hello, world!"
print(text.title()) # Hello, World!
14. str.capitalize(): 将字符串的首字母转换为大写
text = "hello, world!"
print(text.capitalize()) # Hello, world!
15. str.count(): 计算子字符串在字符串中出现的次数
text = "Hello, World! Hello, Python!"
print(text.count("Hello")) # 2
print(text.count("Python")) # 1
16. str.format(): 格式化字符串
name = "John"
age = 30
print("My name is {} and I am {} years old.".format(name, age))
# My name is John and I am 30 years old.
print(f"My name is {name} and I am {age} years old.")
# My name is John and I am 30 years old. (使用 f-string)
5、数字类型
5.1 整数类型 int
- 十进制:-1,0,100 等
- 二进制(以0b开头 后跟 0~1):0b1011(转为十进制为11)
- 八进制(以0o开头 后跟 0~7):0o17(转为十进制为15)
- 十六进制(以0x开头 后跟 0~9, a-f, A-F):0xa3(转为十进制为163)
5.2 浮点数类型 float
- 小数:1.1 ,-2.3等
- 科学计数法:1e6(100 0000), 2e-1(0.2)等
5.3 布尔类型 bool
布尔类型的值只有True和False
类型转换使用bool()方法
当将除0以外的其他数转换为bool类型时,都为True
b = 2
print(bool(b)) # True
b = 1.1
print(bool(b)) # True
b = -3
print(bool(b)) # True
b = 0
print(bool(b)) # False
5.4 复数
复数由实部和虚部构成,虚部的数以j结尾
a = 1 + 2j
print(a)
5.5 数字类型转换
- bin():转换为二进制
- oct():转换为八进制
- int():转换为十进制整数
- hex():转换为十六进制
- float():转换为浮点数
- complex(x):将x转换到一个复数,实数部分为 x,虚数部分为 0。
- complex(x, y):将 x 和 y 转换到一个复数,实数部分为 x,虚数部分为 y。
- bool(x):将 x 转化为布尔值
6、列表 (list)
list是python的四大容器之一,用于存储一组有序的元素的容器,与其他语言中的数组有所区别。
6.1 创建列表
ls = [] # 创建一个空列表
ls_0 = list() # 创建一个空列表
ls_1 = [1, 2, 3, 4, 5] # 创建一个列表
ls_3 = list(range(1,6)) # [1, 2, 3, 4, 5]可以在析构函数里面添加可迭代对象创建列表
ls_4 = [1, 'Two', 3.14, True, False, None] # 创建一个储存不同数据类型的列表
ls_5 = [
['姓名','语文成绩','数学成绩'],
['小王', 78, 90],
['小明', 33, 100]
] # 创建一个嵌套列表
6.2 列表的运算
列表之间可以直接相加,形成一个新列表
# 列表相加
ls_1 = [1, 2, 3]
ls_2 = [4, 5, 6]
ls_3 = ls_1 + ls_2
print(ls_3) # [1, 2, 3, 4, 5, 6]
列表可以追加 +=
ls_1 = [1, 2, 3]
ls_1 += [4, 5, 6]
print(ls_1) # [1, 2, 3, 4, 5, 6]
ls_1 += range(7, 10)
print(ls_1) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
列表可以*产生重复的列表
ls_1 = [1, 2, 3]
ls_2 = ls_1 * 3
print(ls_2) # [1, 2, 3, 1, 2, 3, 1, 2, 3]
列表之间可以相互比较,返回的是bool类型
ls_1 = [1, 2, 3]
ls_2 = [4, 5, 6]
ls_3 = [1, 2, 3]
print(ls_1 == ls_2) # False
print(ls_1 == ls_3) # True
可以用in和not in判断该元素是否存在于列表中,返回的是bool类型
ls_1 = [1, 2, 3]
print(1 in ls_1) # True
print(4 in ls_1) # False
print(1 not in ls_1) # False
print(4 not in ls_1) # True
6.3 列表的增删改查
6.3.1 查询
通过正向索引直接访问,索引下标从0开始,0索引对应列表的第一个数
ls_1 = [1, 2, 3]
print(ls_1[0]) # 输出 1
print(ls_1[1]) # 输出 2
print(ls_1[2]) # 输出 3
通过反向索引访问,-1对应最后一个数
ls_1 = [1, 2, 3]
print(ls_1[-1]) # 输出 3
print(ls_1[-2]) # 输出 2
print(ls_1[-3]) # 输出 1
通过切片操作访问,列表[(开始索引b):(终止索引e)(: (步长s))]
x = [1, 2, 3, 4, 5, 6, 7, 8]
y1 = x[:4] # y1 = [1, 2, 3, 4]
y2 = x[::2] # y2 = [1, 3, 5, 7]
y3 = x[::-1] # y3 = [8, 7, 6, 5, 4, 3, 2, 1]
通过索引遍历整个列表
x = [1, 2, 3, 4, 5, 6, 7, 8]
for i in x:
print(i) # 输出 1 2 3 4 5 6 7 8
6.3.2 增加
通过append()添加数据
x = [1, 2, 3]
x.append(4) # x = [1, 2, 3, 4]
x.append(5) # x = [1, 2, 3, 4, 5]
y = []
for i in range(10):
y.append(i) # y = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
通过insert()插入数据,insrt(索引的位置,要插入的值)
x = [1, 2, 3]
x.insert(0, 0) # 0, 1, 2, 3
x.insert(4, 4) # 0, 1, 2, 3, 4
x.insert(2, 3) # 0, 1, 3, 2, 3, 4
通过extend()添加可迭代对象
x = [1, 2, 3]
x.extend([4, 5, 6]) # x = [1, 2, 3, 4, 5, 6]
x.extend(range(7, 10)) # x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
6.3.3 修改
通过索引直接修改值
x = [1, 2, 3]
x[0] = 5 # x = [5, 2, 3]
x[1] = 6 # x = [5, 6, 3]
6.3.4 删除
通过remove()删除第一次出现在列表中的数据元素,如果x不存在则报错
x = [1, 2, 3]
x.remove(2) # 删除列表中值为2的元素
print(x) # [1, 3]
# x.remove(4) # 报错 x not in list
通过pop()根据索引删除元素,并返回该元素。若不提供索引,默认删除最后一个元素
x = [1, 2, 3]
x.pop(0) # 删除第一个元素
print(x) # [2, 3]
x.pop() # 删除最后一个元素
print(x) # [2]
# x.pop(4) # IndexError: pop index out of range
clear()可以清空列表
x = [1, 2, 3]
x.clear()
print(x) # []
del可以删除指定位置的元素
x = [1, 2, 3]
del x[1] # 删除x[1]
print(x) # [1, 3]
del x # 删除x
# print(x) # NameError: name 'x' is not defined