python print, string manipulation summary

Version difference

  • python 3.x: print() is function and not a keyword anymore. () must be used
print("hello world")
  • python 2.x: print is considered as a keyword, so () is not necessary.
print "hello world"

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.

from __future__ import print_function
print("hello world")

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.

"""abc


def

"""
123456“””abc  def “””

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)

# default sep=' '
print('ab', 'cd', 'ef')             # ab cd ef

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'
print('ab', 'cd', 'ef', sep=' ', end='\n', file=sys.stdout)  # default arg, same with above
print('ab', 'cd', 'ef', sep='SEP')  # abSEPcdSEPef
print('ab', 'cd', 'ef', end='\t')   # default end='\n'
print('gh', 'ij', 'kl', end='\t')
print(('ab', 'cd', 'ef'))           # ab cd ef	gh ij kl	('ab', 'cd', 'ef')

# write to file
f = open('test.txt', 'w')
print('hello world', file=f)

+  -  string addition

print('hello' + 'world' + str(3))  # helloworld3

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.

# % or .format() usage
print('%d %d' % (3, 5))      # 3 5  old style
print('{} {}'.format(3, 5))  # 3 5  new style

Left-align, right-align, truncate

# left align, right align
print('%-10sm%10s' % ('left', 'right',))       # left      m     right
print('{:<10}m{:>10}'.format('left', 'right')) # left      m     right
# truncate
print('%.5s' % ('xylophone',))       # xylop
print('{:.5}'.format('xylophone',))  # xylop

These are the examples only .format() supports

# center align
print('{:^10}'.format('test'))  # '   test   '
# keyword argument
person = {'first': 'Jean-Luc', 'last': 'Picard'}
print('{p[first]} {p[last]} is {age} years old'.format(p=person, age=3))

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.

Leave a Comment

Your email address will not be published. Required fields are marked *