- # 旧版本
- name = "Archer"
- age = 18
- print("姓名:%s, 年龄:%d" %(name, age))
-
- # format格式化输出
- print("姓名:{}, 年龄:{}".format(name, age))
-
- # 新版本
- print(f"姓名:{name}, 年龄:{age}")
-
- a, b = 1, 2
- print(f"a+b={a+b}")
- # 使用=显示变量名
-
- a = "竹筒饭"
- b = 10
- print(f"{a=},{b=}") # a='竹筒饭',b=10
-
-
- name = "竹筒饭"
-
- # ^表示居中显示name,用*补全,总共显示20个字符
- # 旧版本
- print("{:*^20}".format(name))
-
- # 新版本
- print(f"{name:*^20}")
- # 居右显示
- print(f"{name:*>20}")
- # 居左显示
- print(f"{name:*<20}")
-
- # 数值数据格式化
- price = 9.151
- print("{:.2f}".format(price))
- print(f"{price:.2f}")
-
- """
- 所有输出:
- a='竹筒饭',b=10
- ********竹筒饭*********
- ********竹筒饭*********
- *****************竹筒饭
- 竹筒饭*****************
- 9.15
- 9.15
- """
方法名 | 功能 |
str.removeprefix() | 如果str以它开头,将返回一个删除过前缀的新字符串,否则它将返回原始字符串 |
str.removesuffix() | 如果str以其结尾,则返回删除过后缀的新字符串,否则它将返回原始字符串 |
- info = "Archer"
-
- print(info.removeprefix("Ar")) # cher
- print(info.removeprefix("Saber")) # Archer
-
- print(info.removesuffix("er")) # Arch
- print(info.removesuffix("Saber")) # Archer
在Python3.10中,针对字典的三个方法items、keys、values都增加了一个mapping属性。
- mydict = {"one":1, "two":2, "three":3}
-
- # 旧版本
- print(f"{mydict.keys()}\n{mydict.values()}\n{mydict.items()}")
-
- # 新版本
- keys = mydict.keys()
- values = mydict.values()
- items = mydict.items()
- print(f"{keys.mapping}\n{values.mapping}\n{items.mapping}")
-
- """
- 输出结果
- # 旧版本
- dict_keys(['one', 'two', 'three'])
- dict_values([1, 2, 3])
- dict_items([('one', 1), ('two', 2), ('three', 3)])
- # 新版本
- {'one': 1, 'two': 2, 'three': 3}
- {'one': 1, 'two': 2, 'three': 3}
- {'one': 1, 'two': 2, 'three': 3}
- """
- dict1 = {"name": "竹筒饭"}
- dict2 = {"age": 18}
-
- dict1.update(dict2)
- print(dict1) # {'name': '竹筒饭', 'age': 18}
-
- dict3 = dict1 | dict2
- print(dict3) # {'name': '竹筒饭', 'age': 18}
-
- dict1 |= dict2
- print(dict1) # {'name': '竹筒饭', 'age': 18}
match...case结构化模式匹配。类似于Java中的switch...case
- status = 300
-
- match status:
- case 200:
- print("访问成功")
- case 404:
- print("页面丢失")
- case _:
- print("阿巴阿巴..")
- # 阿巴阿巴..
- person1 = ("Archer", 23, "male")
- person2 = ("Saber", 22, "female")
- person3 = ("竹筒饭", 26, "***")
-
-
- def match_func(person):
- match person:
- case (name, _, "female"):
- print(f"{name} is woman")
- case (name, _, "male"):
- print(f"{name} is man")
- case (name, _, gender):
- print(f"{name} is {gender}")
-
-
- match_func(person1)
- match_func(person2)
- match_func(person3)
-
- # Archer is man
- # Saber is woman
- # 竹筒饭 is ***