• Python编码规范06-基础规范--字符串


    1、字符串格式化

    Yes: x = a + b
         x = '%s, %s!' % (imperative, expletive)
         x = '{}, {}!'.format(imperative, expletive)
         x = 'name: %s; score: %d' % (name, n)
         x = 'name: {}; score: {}'.format(name, n)
    No: x = '%s%s' % (a, b)  # use + in this case
        x = '{}{}'.format(a, b)  # use + in this case
        x = imperative + ', ' + expletive + '!'
        x = 'name: ' + name + '; score: ' + str(n)

    2、字符串累加

    避免在循环中用+和+=操作符来累加字符串. 由于字符串是不可变的, 这样做会创建不必要的临时对象, 并且导致二次方而不是线性的运行时间. 作为替代方案, 你可以将每个子串加入列表, 然后在循环结束后用 .join 连接列表.

    Yes: items = ['<table>']
         for last_name, first_name in employee_list:
             items.append('<tr><td>%s, %s</td></tr>' % (last_name, first_name))
         items.append('</table>')
         employee_table = ''.join(items)
    No: employee_table = '<table>'
        for last_name, first_name in employee_list:
            employee_table += '<tr><td>%s, %s</td></tr>' % (last_name, first_name)
        employee_table += '</table>'

     3、字符串引号一致性

    在同一个文件中, 保持使用字符串引号的一致性. 使用单引号'或者双引号"之一用以引用字符串, 并在同一文件中沿用. 在字符串内可以使用另外一种引号, 以避免在字符串中使用.

    Yes:
         Python('Why are you hiding your eyes?')
         Gollum("I'm scared of lint errors.")
         Narrator('"Good!" thought a happy Python reviewer.')
    No:
         Python("Why are you hiding your eyes?")
         Gollum('The lint. It burns. It burns us.')
         Gollum("Always the great lint. Watching. Watching.")



  • 相关阅读:
    正则表达式例子
    addevent兼容函数 && 阻止默认行为 && 阻止传播
    addevent
    区分总结innerHeight与clientHeight、innerWidth与clientWidth、scrollLeft与pageXOffset等属性
    setattribute兼容
    随机分配位置
    浏览器类型
    统计一个字符串中相同字符的个数
    Appium发送中文或其他语言的问题
    Appium同时连接多台手机进行测试(多线程)
  • 原文地址:https://www.cnblogs.com/mazhiyong/p/12504817.html
Copyright © 2020-2023  润新知