【python基础】13-文档字符串


风格指南

引用自Python文档 - 编码风格

  • 使用4-空格缩进,不用制表符
  • 包裹行让它们不超过79字符
  • 使用空行分隔函数、类和函数内较大的代码块
  • 尽量注释
  • 使用文档字符串
  • 逗号后、操作符周围使用空格
  • 统一命名类和函数
    • 传统是对类使用骆驼拼写法,函数和方法使用小写和下划线

风格指南


回文示例

#!/usr/bin/python3

"""
Asks for user input and tells if string is palindrome or not

Allowed characters: alphabets and punctuations .,;:'"-!?
Minimum alphabets: 3 and cannot be all same

Informs if input is invalid and asks user for input again
"""

import re

def is_palindrome(usr_ip):
    """
    Checks if string is a palindrome

    ValueError: if string is invalid

    Returns True if palindrome, False otherwise
    """

    # remove punctuations & whitespace and change to all lowercase
    ip_str = re.sub(r'[\s.;:,\'"!?-]', r'', usr_ip).lower()

    if re.search(r'[^a-zA-Z]', ip_str):
        raise ValueError("Characters other than alphabets and punctuations")
    elif len(ip_str) < 3:
        raise ValueError("Less than 3 alphabets")
    else:
        return ip_str == ip_str[::-1] and not re.search(r'^(.)\1+$', ip_str)

def main():
    while True:
        try:
            usr_ip = input("Enter a palindrome: ")
            if is_palindrome(usr_ip):
                print("{} is a palindrome".format(usr_ip))
            else:
                print("{} is NOT a palindrome".format(usr_ip))
            break
        except ValueError as e:
            print('Error: ' + str(e))

if __name__ == "__main__":
    main()
  • 首个三引号括起的字符串标记了整个程序的文档字符串
  • 第二个是is_palindrome()函数特定的文档字符串
$ ./palindrome.py
Enter a palindrome: as2
Error: Characters other than alphabets and punctuations
Enter a palindrome: "Dammit, I'm mad!"
"Dammit, I'm mad!" is a palindrome

$ ./palindrome.py
Enter a palindrome: a'a
Error: Less than 3 alphabets
Enter a palindrome: aaa
aaa is NOT a palindrome
  • 让我们看下文档字符串怎么作为帮助使用
  • 注意文档字符串是怎么自动格式化的
>>> import palindrome
>>> help(palindrome)

Help on module palindrome:

NAME
    palindrome - Asks for user input and tells if string is palindrome or not

DESCRIPTION
    Allowed characters: alphabets and punctuations .,;:'"-!?
    Minimum alphabets: 3 and cannot be all same

    Informs if input is invalid and asks user for input again

FUNCTIONS
    is_palindrome(usr_ip)
        Checks if string is a palindrome

        ValueError: if string is invalid

        Returns True if palindrome, False otherwise

    main()

FILE
    /home/learnbyexample/python_programs/palindrome.py
  • 也可以直接获取函数帮助
>>> help(palindrome.is_palindrome)

Help on function is_palindrome in module palindrome:

is_palindrome(usr_ip)
    Checks if string is a palindrome

    ValueError: if string is invalid

    Returns True if palindrome, False otherwise
  • 测试函数
>>> palindrome.is_palindrome('aaa')
False
>>> palindrome.is_palindrome('Madam')
True

>>> palindrome.main()
Enter a palindrome: 3452
Error: Characters other than alphabets and punctuations
Enter a palindrome: Malayalam
Malayalam is a palindrome

进一步阅读

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Python是一种对代码风格很重视的语言,从缩进就能看出这一点,Python强调易于理解。最近在负责代码重构的工作...
    知曰阅读 11,309评论 1 85
  • 原文链接 《Python数据分析》(Python for Data Analysis, 2nd Edition)第...
    李绍俊阅读 8,621评论 0 5
  • 更新时间:2016/5/13 介绍 本文档所提供的编码规范,适用于主要的Python发行版中组成标准库的Pytho...
    超net阅读 5,925评论 0 15
  • # Python 资源大全中文版 我想很多程序员应该记得 GitHub 上有一个 Awesome - XXX 系列...
    aimaile阅读 26,650评论 6 427
  • 昨天在荔枝上录了三个节目,最后只剩下一个。因为录好后我回过头去听的时候,发现中间有杂音录了进去,是我不仔细。然而已...
    菀蔸阅读 247评论 0 0