Python Tutorial-Formatting

In this tutorial we discuss formatting of variables. There’s not much to explain so I’ll just get started by showing you some examples.

Formatting Numbers as Strings

Your output should be Your total is 525.670000 and Your total is 525.68. Let’s explain this. In the first print statement we told Python that we wanted to format the number 325.67 as a floating point number the way Python defines a floating point number. We do this first by telling Python we want to declare the number a floating point number with the %f’. The % on the right side tells Python what you want to apply the formatting too.

The second print statement is similar, but now we added a .2 in front of the f. We are telling Python that we want to format the number after the % should only have 2 digits following the decimal point.

Formatting Strings

Formatting strings is done the exact same way with one minor exception. Instead of using an f we use an s. Check this out.

Your output is abcdedfghijklmno. We truncated the output to the 15th character. Make sense? Try it out for yourself. Have fun, have a blast..just come back when you’re done.