Home /Python/Formatting

Formatting

We waited a little bit to talk about formatting because it might get a little intense with how much you can do and how easily you can do things withvariables in Python. Formatting in Python is a little bit odd at first. But, once you get accustomed to it, you'll be glad you did.

Formatting Numbers as Strings

Example

print('The order total comes to %f' % 123.44) print('The order total comes to %.2f' % 123.444)

Result:
The order total comes to 123.440000
The order total comes to 123.44

Ya, I told you it's a little weird. The f following the first % is short for float here because we have floating numbers and Python has a specific way of dealing with formatting decimals. The left % tells Python where you want to put the formatted string. The value following the right % is the value that we want to format. So, Python reads through the string until it gets to the first % then Python stops and jumps to the next %. Python takes the value following the second % and formats it according to the first %. Finally, Python places that second value where the first % is. We can use a single value such as a string or a number. We can also use a tuple of values or a dictionary.

Formatting Strings

Strings are just like how we were formatting the numbers above except we will use a s for string instead of an f like before. Usually, you will only want to format a string to limit the number of characters. Let's see it in action:

Example

a ="abcdefghijklmnopqrstuvwxyz" print('%.20s' % a)

Result: abcdefghijklmnopqrst