一些基本类型的秘诀
1.整数
(1)进制数的转换
x = 16
print(bin(x)) # 转换为二进制,带0b前缀
print(f"{x: x}") # b:二进制,o:八进制,x:十六进制,不带前缀
print(int(f'{x: b}', 2)) # int(str, n), 将n(int类型)的str转换为10进制数
"""
[out]
0b10000
10
16
"""
2.字符串
(1) 多重清洗
wash_dict = {
ord('\t'): ' ', ord('\n'): ' ', ord('.'): ''
}
test = "I\tlove\npython..!"
print(test)
print(test.translate(wash_dict))
"""
[out]
I love
python..!
I love python!
"""
(2) 字符串对齐
s = "Menu"
print(s.center(20, "*")) # 居中对齐
print(f"{s:*>20s}")
"""
[out]
********Menu********
****************Menu
"""
(3) 字符串的插入–使用模板
from string import Template
class LogInfo:
def __init__(self, time_, site, user, action, detail):
self.time_ = time_
self.site = site
self.user = user
self.action = action
self.detail = detail
log_info_template = Template("$time_-$site-$user-$action-$detail")
logInfo = LogInfo('2021/11/21/14:20', "Jason", '/superme', 'buy', ['shirt', "¥123"])
new_log = log_info_template.substitute(vars(logInfo))
print(new_log)
"""
[out]
2021/11/21/14:20-Jason-/superme-buy-['shirt', '¥123']
"""