流畅的Python,Fluent Python,书中错误记录。

书p129页,示例5-15

def clip(text:str, max_len:'int' =8) -> str:
    '''
    :param text: 在max_len前面或后面的第一个空格处截断文本
    '''
    end = None
    if len(text) > max_len:
        space_before = text.rfind(' ', 0, max_len)  # 从右向左找,rfind,对应max_len前面的第一个空格
        if space_before >= 0:
            end = space_before
        else:
            space_after = text.find(' ', max_len) # 找max_len的后面了
            if space_after >= 0:
                end = space_after
    if end is None:   # 没有找到,很聪明定义了一个None的开关
        end = len(text)
    return text[:end].rstrip()

 if space_after >= 0: end = space_after

缩进错误。

p566页,示例A.2

import sys

MAX_BITS = len(format(sys.maxsize, 'b'))  # 确定位数,我是64位
print('%s-bit Python build' % (MAX_BITS + 1))


def hash_diff(o1, o2):
    h1 = '{:0>{}b}'.format(hash(o1), MAX_BITS)  # 取出哈希值,用2进制格式化输出,右对齐,空位用0填充
    # print(h1)
    h2 = '{:>0{}b}'.format(hash(o2), MAX_BITS)
    # print(h2)
    diff = ''.join('|' if b1 != b2 else ' ' for b1, b2 in zip(h1, h2))  # 通过zip压缩循环取值,对比是否相等
    # print(diff)   相等留空,不想等划线
    count = '|={}'.format(diff.count('|'))  # 统计不想等的个数
    width = max(len(repr(o1)), len((repr(o2))), 8)  # 确定起头的宽度
    # print(width)
    sep = '-' * (width * 2 + MAX_BITS)  # 最后的过度线,
    # print(sep)
    return '{!r:{width}}=>{}\n  {}{:{width}} {} \n{!r:{width}}=>{}\n{}'.format(
        o1, h1, ' ' * (width), diff, count, o2, h2, sep, width=width)
    # 这个格式化最骚,首先标题订宽度用width,接着输入原始数字o1,=>输出哈希值,第二行输出|竖线,后面输出不同的数量
    # 第三排逻辑跟第一排一样,最后换行输出------线,这个太骚的格式化输出了


if __name__ == '__main__':
    print(hash_diff(1,True))
    print(hash_diff(1, 1.01))
    print(hash_diff(1.0, 1))
    print(hash_diff('a', 'A'))
    print(hash_diff('a1', 'a2'))
    print(hash_diff('sidian', 'sidian'))

 return '{!r:{width}}=>{}\n {}{:{width}} {} \n{!r:{width}}=>{}\n{}'.format( o1, h1, ' ' * (width), diff, count, o2, h2, sep, width=width)

return的格式化输出中多了一个{}

猜你喜欢

转载自www.cnblogs.com/sidianok/p/12061114.html
今日推荐