DEV Community

Super Kai (Kazuya Ito)
Super Kai (Kazuya Ito)

Posted on • Edited on

format in Python (1)

Buy Me a Coffee

*Memo:

format() can create a string with zero or more positional and/or keyword arguments, then format the string as shown below:

*Memo:

  • The 1st arguments are *args(Optional-Default:()-Type:Any):
    • Don't use any keyword like *args, args, etc.
  • The 2nd arguments are **kwargs(Optional-Default:{}-Type:Any):
    • Don't use any keyword like **kwargs, kwargs, etc.

<{} & {index} & {key}>:

*Memo:

  • A {} can output a positional argument with limit:
    • For example, if there are three positional arguments, three {} can be used as maximum.
  • A {index} can output a positional argument with no limit.
  • A {key} can output a keyword argument with no limit.
  • Both {} and {index} cannot be used at the same time.
  • {} doesn't accept any spaces.
print('-{}-{}-{}-{k1}-{k2}-'.format('A', 'BC', 'DEF', k1='GH', k2='I')) print('-{0}-{1}-{2}-{k1}-{k2}-'.format('A', 'BC', 'DEF', k1='GH', k2='I')) # -A-BC-DEF-GH-I-  print('-{}-{k2}-{}-{k1}-{}-'.format('A', 'BC', 'DEF', k1='GH', k2='I')) print('-{0}-{k2}-{1}-{k1}-{2}-'.format('A', 'BC', 'DEF', k1='GH', k2='I')) # -A-I-BC-GH-DEF-  print('-{k2}-{k1}-{2}-{1}-{0}-'.format('A', 'BC', 'DEF', k1='GH', k2='I')) # -I-GH-DEF-BC-A-  print('-{1}{0}-{k2}{0}{1}-{2}{2}-'.format('A', 'BC', 'DEF', k1='GH', k2='I')) # -BCA-IABC-DEFDEF-  print(''.format('A', 'BC', 'DEF', k1='GH', k2='I')) print(''.format()) # Nothing  print('-{}-{}-{}-{}-'.format('A', 'BC', 'DEF', k1='GH', k2='I')) # IndexError: Replacement index 3 out of range for positional args tuple  print('-{0}-{}-{2}-'.format('A', 'BC', 'DEF', k1='GH', k2='I')) # ValueError: cannot switch from manual field specification # to automatic field numbering  print('{ }'.format('ABC')) # KeyError: ' '  print('{ k }'.format(k='ABC')) # KeyError: ' k ' 
Enter fullscreen mode Exit fullscreen mode
v1 = ['A', 'BC', 'DEF'] v2 = {'k1':'GH', 'k2':'I'} print('-{}-{}-{}-{k1}-{k2}-'.format(*v1, **v2)) print('-{0}-{1}-{2}-{k1}-{k2}-'.format(*v1, **v2)) # -A-BC-DEF-GH-I-  print('-{}-{k2}-{}-{k1}-{}-'.format(*v1, **v2)) print('-{0}-{k2}-{1}-{k1}-{2}-'.format(*v1, **v2)) # -A-I-BC-GH-DEF-  print('-{k2}-{k1}-{2}-{1}-{0}-'.format(*v1, **v2)) # -I-GH-DEF-BC-A-  print('-{1}{0}-{k2}{0}{1}-{2}{2}-'.format(*v1, **v2)) # -BCA-IABC-DEFDEF-  print(''.format(*v1, **v2)) print(''.format()) # Nothing 
Enter fullscreen mode Exit fullscreen mode

*Format Specification can be used with format():

v = -0.0 print('"{:0>-z#010_.0f}"'.format(v)) print('"{:0>-z#10_.0f}"'.format(v)) print('"{:>-z#010_.0f}"'.format(v)) # "000000000."  print('"{0:0>-z#010_.0f}"'.format(v)) print('"{0:0>-z#10_.0f}"'.format(v)) print('"{0:>-z#010_.0f}"'.format(v)) # "000000000."  print('"{:0>-z#010_.0f}" "{:0>-z#10_.0f}" "{:>-z#010_.0f}"'.format(v, v, v)) print('"{0:0>-z#010_.0f}" "{1:0>-z#10_.0f}" "{2:>-z#010_.0f}"'.format(v, v, v)) # "000000000." "000000000." "000000000." 
Enter fullscreen mode Exit fullscreen mode

<index[index] & key[index]>:

v = ['A', 'B', 'C', 'D'] print('{0}\n- {0[0]} - {0[1]} - {0[2]} - {0[3]}'.format(v)) print('{k}\n- {k[0]} - {k[1]} - {k[2]} - {k[3]}'.format(k=v)) # ['A', 'B', 'C', 'D'] # - A - B - C - D 
Enter fullscreen mode Exit fullscreen mode
v1 = [['A', 'B'], ['C', 'D']] v2 = '{0}\n- {0[0]} - {0[1]}\n- {0[0][0]} - {0[0][1]} - {0[1][0]} - {0[1][1]}' v3 = '{k}\n- {k[0]} - {k[1]}\n- {k[0][0]} - {k[0][1]} - {k[1][0]} - {k[1][1]}' print(v2.format(v1)) print(v3.format(k=v1)) # [['A', 'B'], ['C', 'D']] # - ['A', 'B'] - ['C', 'D'] # - A - B - C - D 
Enter fullscreen mode Exit fullscreen mode

<index[key] & key[key]>:

*key cannot have "" or ''.

v = {'name':'John', 'age':36} print('{0}\n- {0[name]} - {0[age]}'.format(v)) print('{k}\n- {k[name]} - {k[age]}'.format(k=v)) # {'name': 'John', 'age': 36} # - John - 36  print('{0["name"]}'.format(v)) # KeyError: '"name"'  print("{k['age']}".format(k=v)) # KeyError: "'age'" 
Enter fullscreen mode Exit fullscreen mode
v1 = {'person':{'name':'John', 'age':36}} v2 = '{0}\n- {0[person]}\n- {0[person][name]} - {0[person][age]}' v3 = '{k}\n- {k[person]}\n- {k[person][name]} - {k[person][age]}' print(v2.format(v1)) print(v3.format(k=v1)) # {'person': {'name': 'John', 'age': 36}} # - {'name': 'John', 'age': 36} # - John - 36 
Enter fullscreen mode Exit fullscreen mode

<index.key & key.key>:

*key cannot be called with ().

import math print('{0.pi} - {k.pi}'.format(math, k=math)) # 3.141592653589793 - 3.141592653589793  print('{0.pow}'.format(math)) print('{k.pow}'.format(k=math)) # <built-in function pow>  print('{0.pow(3, 2)}'.format(math)) print('{k.pow(3, 2)}'.format(k=math)) # AttributeError: module 'math' has no attribute 'pow(3, 2)' 
Enter fullscreen mode Exit fullscreen mode

<!s & !r & !a>:

*Memo:

  • !s is str() which can create a string.
  • !r is repr() which can create a printable string.
  • !a is ascii() which can create the printable string of ASCII characters. *Non-ASCII characters are represented with \x, \u, or \U escape.
v = "Jφhи\tSмiтh" print("{!s}".format(v)) print("{0!s}".format(v)) print("{k!s}".format(k=v)) # Jφhи Sмiтh  print("{!r}".format(v)) print("{0!r}".format(v)) print("{k!r}".format(k=v)) # 'Jφhи\tSмiтh'  print("{!a}".format(v)) print("{0!a}".format(v)) print("{k!a}".format(k=v)) # 'J\u03c6h\u0438\tS\u043ci\u0442h' 
Enter fullscreen mode Exit fullscreen mode
v = 'I\'m Jφhи\tSмiтh.' print('{!s}'.format(v)) print('{0!s}'.format(v)) print('{k!s}'.format(k=v)) # I'm Jφhи Sмiтh.  print('{!r}'.format(v)) print('{0!r}'.format(v)) print('{k!r}'.format(k=v)) # "I'm Jφhи\tSмiтh."  print('{!a}'.format(v)) print('{0!a}'.format(v)) print('{k!a}'.format(k=v)) # "I'm J\u03c6h\u0438\tS\u043ci\u0442h." 
Enter fullscreen mode Exit fullscreen mode

<{{ & }}>

*Memo:

  • { can escape {.
  • } can escape }.
print('The bracket {{ is escaped.'.format()) # The bracket { is escaped.  print('The bracket }} is escaped.'.format()) # The bracket } is escaped.  print('The {{brackets}} are escaped.'.format()) # The {brackets} are escaped. 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)