python print, string manipulation summary

 

Version difference

  • python 3.x: print() is function and not a keyword anymore. () must be used.

  • python 2.x: print is considered as a keyword, so () is not necessary.

The above syntax cannot be used in python 3!
But you can use future module import if you want to use print as a function for python 3 compatibility.

Summary: It is better to use print() for future compatibility from now on.

Ref:

Single quotation and double quotation for string

There is no difference between 'word' and "word" in python.
But for triple quoted strings, use double quotation like below to follow PEP 257.

String Quotes

In Python, single-quoted strings and double-quoted strings are the same. This PEP does not make a recommendation for this. Pick a rule and stick to it. When a string contains single or double quote characters, however, use the other one to avoid backslashes in the string. It improves readability.

For triple-quoted strings, always use double quote characters to be consistent with the docstring convention in PEP 257 .

Cite from PEP 8 — Style Guide for Python Code

Ref: Is there any difference between “string” and ‘string’ in Python? [duplicate]

 

print basic functionality

Explains behavior of print function in python 3 (or use from __future__ import print_function in python 2)

comma: ,  ー  variable arguments

print function can take several arguments and they are printed with space (separate word specified by sep)

 

optional arguments

  • sep: specify separator word. default value is ' '
  • end: end of the text. default value is '\n'
  • file: output stream. default value is 'sys.stdout'

 

+  -  string addition

string can be concatenated with +. For number, you need to cast with str().

% and .format()  ー  formatting string

Refer PyFormat page for detailed explanation and its usage example.

Summary: use .format() since it is newer method than % and supports more functionality (for example center alignment, keyword arguments etc).

Ex.

Left-align, right-align, truncate

 

These are the examples only .format() supports

 

Conclusion and summary

  • Use print() for python 3 compatibility.
    write from __future__ import print_function in python 2
  • Use , (multiple argument) when you want to print out several variables.
  • Use .format() instead of % for formatting string.

Sponsored Links

Leave a Reply

Your email address will not be published.