Introduction to Python – Data Structures (Input and Output)

Categories Devnet, Python
  • You can format the data that is output from python. The data can be returned as human readable output, the data can be returned to a file to be used later. This can be done through expression statements, the print() function or using the write() method for file objects.

Oh, you Fancy! huh?

  • Often you’ll want more control over the formatting of your output than simply printing space-separated values. There are several ways to format output.
  • Formatted string literals, also known as f-strings allow you to include the value of an expression inside a string. The format is to start with an f or F before the string and adding curles to the expression ie: {expression}
  • An optional format specifier can follow the expression. This allows greater control over how the value is formatted. The following example rounds pi to three places after the decimal:
  • Passing an integer after the ':' will cause that field to be a minimum number of characters wide. This is useful for making columns line up.
  • There are many other formats you can use on literal strings.

String() Format Method()

  • The str.format() method works as follows: