Python string format

When you google `python format`, you’ll see a lot of articles. Here I want to make a short summary and present the formatting methods in a proper way.
Chinese version is on my blog already: Python Handling Strings

In general, there are three ways: %, .format(), and f-string. We’ll discuss their use and give examples for you.

% operator

This is the oldest way to format your string and this should go with print() function. The placeholder is your % followed by the format.

  • %d: decimal
  • %o: octal
  • %x: octal
  • %e: exponential
  • %f: floats
  • %s: string

In our examples, you can see the % plays as a placeholder in the print function. and what after % is the rule to format your input. However, if you have a long string to format, you have to type many % and it becomes hard to understand each variable. The readability is terrible.

.format()

In python 2+, .format() method is released. It provides better readability and thus a cleaner way to format.

Now the placeholder is {} with the format inside. Because now you can have variables inside the {}, it enhances the flow to read one’s code. However, again, the if there are tons of inputs, the format function would be incredibly long.

f-string

Fancier Output Formatting (according to python documents). This formatting method started in python 3.6 and it provides the best format readability.

The placeholder remains to be {} but we don’t have to add .format at the end. Instead, the variable can be put inside the {} intuitively.

What to be noted is that combining raw string and f string may be a good way in your code. Because things like ‘\n’ would be different in raw string and f-string.

Take home message

if your program requires to print a lot of information of your variables, f-string is your good friend, especially using f’’’ ‘’’ to print a paragraph. It saves a lot of time to track each variable in the string. But one uses f-string should take care of the characters like \n we mentioned.

--

--

--

Graduated master in astronomy. Wanna code a better world. 天文所畢業,致力使世界更好。

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Lin Han Tang

Lin Han Tang

Graduated master in astronomy. Wanna code a better world. 天文所畢業,致力使世界更好。

More from Medium

The `getattr` function in Python

Python Class Object Oriented Programming Tutorial: How To Program A Vending Machine

Python simple debugging beyond print() with Icecream

Python String isalpha() method