总结一些常用的关于 python 3 的知识点
字符串 str
字符串新建
a = "a" * 5 # "aaaaa"
字符串更新 - string is immutable in python
a = "abcde"
b = a[:2] + "X" + a[3:] # "abXde"
字符串 - strip -> str
s = "/leet"
s.strip("/")
print(s) # "/leet"
new_s = s.strip("/")
print(new_s) # "leet" because strip will return a new string
字符串合并 - join
a = "".join(["y", "e", "s"]) # yes
a = ",".join(["A", "A", "A"]) #A,A,A
字符串分割 - 1 - 无delimiter(即把string拆成 a list of chars in that string)
a = "Hello wor"
aa = list(a) # ["H", "e", "l", "l", "o", " ", "w", "o", "r"]
字符串分割 - 2 - 有delimiter - split -> List[str]
s = "/leet"
print(s.split("/")) # ["", "leet"]
s = "/leet/code"
print(s.split("/")) # ["", "leet", "code"]
s = "leet"
print(s.split("/")) # [leet"]
s = "leet/code"
print(s.split("/")) # [leet", "code"]
s = "leet/code/"
print(s.split("/")) # [leet", "code", ""]
字典 / 哈希
官方API Built-in Types — Python 3.10.4 documentation
# 初始化
new_dict = {} # new dict with empty items
new_dict = dict() # new dict with empty items
new_dict = {"a": 1, "b": 2}
# 增 / 改
new_dict[new_key] = new_value
# 删 pop(key [,defaut_value]) -> value
new_dict.pop(some_key) # error if key not found
new_dict.pop(some_key, default_value)
# 查
new_dict.get(some_key, default_value_when_key_not_found)
new_dict.get(some_key) # error when key not found
# 容量
len(my_dict)
# 最值
max(my_dict, key=my_dict.get) # find the key with the max value
# 排序
my_dict = {'a': 2, 'b': 1, 'c': 3}
sorted(my_dict.items(), key=lambda item: item[1]) # [('b', 1), ('a', 2), ('c', 3)]
sorted(my_dict, key=my_dict.get) # ['b', 'a', 'c']
# 循环
for key in my_dict:
for value in my_dict.values():
for key, value in my_dict.items():