python (python3) 基础知识点 (更新中)

总结一些常用的关于 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():

组合 set

官方 API Built-in Types — Python 3.10.4 documentation

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值