• Martin Thoma
  • Home
  • Categories
  • Tags
  • Archives
  • Support me

Formatting Strings in Python

Contents

  • Formatting Strings in Python
    • Print directly
    • Save as string
    • Named formatting
    • Date and Time
    • Lists
    • str and repr
    • Formatters
    • Columns
    • Resources

In Python, you can use the following ways to format Strings:

Print directly

Printing them directly (just like printf in C):

birthday = 28
month = "April"
year = 1990
print("My birthday is the %i-th %s %i." % (birthday, month, year))

The first string contains the rules how to format. %i means that the first argument in the following tuple should be interpreted as a integer. The second one %s should be interpreted as a string and the third one again as a integer.

Save as string

>>> a = "Why is %i the answer?" % 42
>>> a
'Why is 42 the answer?'

Named formatting

You might prefer named formatting:

>>> "{guy} loves {girl}.".format(girl="Marie", guy="Martin")
'Martin loves Marie.'

You can also store this first in a dictionary an unpack it:

>>> myDictionary = {"girl":"Marie","guy": "Martin","other":"Internet"}
>>> "{guy} loves {girl}.".format(girl="Marie", guy="Martin")
'Martin loves Marie.'

Date and Time

You can format time any way you like, just look at this reference.

Lists

Question: I would like to print a list! How do I do that? Answer: Convert your list to a string

>>> myList = [1,2,3]
>>> print("Your list: %s" % (str(myList)))
Your list: [1, 2, 3]

str and repr

When you build your own objects, you should add an implementation for the method str and repr. The first one should return a string representation that is human readable of the object, the second one should return a string that identifies the object.

Formatters

%i Integer
>>> print("%i" % (123))
123
%s String
>>> print("%s" % ("Martin"))
Martin
%o Int as octal
>>> print("%o" % (123.123))
173
%x Int as hexadecimal (lower case)
>>> print("%x" % (123.123))
7b
%X Int as hexadecimal (upper case)
>>> print("%X" % (123.123))
7B
%f Floating point
>>> print("%f" % (123.123))
123.123000
%.2f Floating point with two decimal places
>>> print("%.2f" % (123.123))
123.12
%e Floating point in scientific notation
>>> print("%e" % (123.123))
1.231230e+02
%% Percent sign
>>> print("%i%%" % (65))
65%
%6.2f Print a float with 2 decimal places. Add spaces if this has less than 6 characters.
>>> print("%6.2f" % (65.123))
 65.12

Columns

my_list = [
    ("Easybox 1234", 54, "DC:9F:DB:B2:B1:1C"),
    ("FRITZ!Box 6360 Cable", 12, "24:65:11:06:71:54"),
    ("wkit-802.1x", 15, "A0:D3:C1:9F:FF:11"),
]
header = "{0:<20}{1:>6}{2:>20}".format("SSID", "Signal", "HwAddress")
print(header)
print("-" * len(header))
for ssid, signal, hwaddress in my_list:
    print("{0:<20}{1:>6}{2:>20}".format(ssid, str(signal) + "%", hwaddress))

results in

SSID                Signal           HwAddress
----------------------------------------------
Easybox 1234           54%   DC:9F:DB:B2:B1:1C
FRITZ!Box 6360 Cable   12%   24:65:11:06:71:54
wkit-802.1x            15%   A0:D3:C1:9F:FF:11

Resources

  • pyformat.info
  • Format Specification Mini-Language
  • Time formatting
  • Pretty Print

Published

Nov 7, 2013
by Martin Thoma

Category

Code

Tags

  • Python 141

Contact

  • Martin Thoma - A blog about Code, the Web and Cyberculture
  • E-mail subscription
  • RSS-Feed
  • Privacy/Datenschutzerklärung
  • Impressum
  • Powered by Pelican. Theme: Elegant by Talha Mansoor