Usage
def print_usage():
print("hello - print out a message\n")
print("Usage: hello.py [-h] [-o OUTPUT]\n")
print("Options:")
print("-o OUTPUT, --output=OUTPUT output the given string")
print("-h --help show this help message and exit")
if __name__ == "__main__":
print_usage()
Convert multiple prints into a single
printstatement: “Simple is better than complex.”Use
+to concatenate multiple strings, wrapping one long line with\: “Complex is better than complicated.”Add missing
\nto break lines apart: “Readability counts.”
def print_usage():
usage_message = "hello - print out a message\n\n" + \
"Usage: hello.py [-h] [-o OUTPUT]\n\n" + \
"Options:\n" + \
"-o OUTPUT, --output=OUTPUT output the given string\n" + \
"-h --help show this help message and exit"
print(usage_message)
Use implicit line wrapping instead of
\to wrap lines: PEP 8 and “Readability counts.” and “Simple is better than complex.”Line up all strings: “Readability counts.”
Remove
+signs, relying on implicit string concatenation (warning: this may be seen as un-Pythonic by some): “Simple is better than complex.”
def print_usage():
usage_message = (
"hello - print out a message\n\n"
"Usage: hello.py [-h] [-o OUTPUT]\n\n"
"Options:\n"
"-o OUTPUT, --output=OUTPUT output the given string\n"
"-h --help show this help message and exit"
)
print(usage_message)
Use multi-line string: “Simple is better than complex.”
Replace
\nwith actual newlines: “Simple is better than complex.”Strip whitespace from ends of the string to compensate for extra newlines: “Complex is better than complicated.”
def print_usage():
usage_message = """
hello - print out a message
Usage: hello.py [-h] [-o OUTPUT]
Options:
-o OUTPUT, --output=OUTPUT output the given string
-h --help show this help message and exit"""
print(usage_message.strip())
Make a list of strings, one for each line and join them with
\nRemove now unnecessary
strip
def print_usage():
usage_message = "\n".join([
"hello - print out a message",
"",
"Usage: hello.py [-h] [-o OUTPUT]",
"",
"Options:",
"-o OUTPUT, --output=OUTPUT output the given string",
"-h --help show this help message and exit"
])
print(usage_message)
Make a multi-line docstring stating the usage information for this program: “Explicit is better than implicit.”
Print out the docstring as usage, stripping extra whitespace: “Readability counts.” and “Simple is better than complex.”
"""
hello - print out a message
Usage: hello.py [-h] [-o OUTPUT]
Options:
-o OUTPUT, --output=OUTPUT output the given string
-h --help show this help message and exit
"""
def print_usage():
print(__doc__.strip())