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 |
|
%s |
String |
|
%o |
Int as octal |
|
%x |
Int as hexadecimal (lower case) |
|
%X |
Int as hexadecimal (upper case) |
|
%f |
Floating point |
|
%.2f |
Floating point with two decimal places |
|
%e |
Floating point in scientific notation |
|
%% |
Percent sign |
|
%6.2f |
Print a float with 2 decimal places. Add spaces if this has less than 6 characters. |
|
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