CodeLearn PythonPythonPython GUI

Learn Three Different Ways of Formatting String in Python!

In this post, we will learn three different ways of formatting string in Python as well as which one you should use.

The old way

In the beginning of Python, there was only one way to format strings – by using %s. Let’s an example:

%s serves as a placeholder for a value in name variable. More variable could be embedded by adding more %s in the string and separating variables by comma (,). This can work fine for a single variable, but if we add more variables, it can quickly result in a mess.

The good way

Later, Python developers introduced format method on string which works in similar way, but is way cleaner. An example:

We use curly braces as a placeholder, instead of %s. Like with %s we can specify more curly braces at different places to embed more variables. But once again, this can be improved and just like %s, it can quickly become messy.

The modern way

Starting with Python 3.6, f-string feature was introduced in the language which allows developer to format strings in a nice, maintainable and more readable way.

fstring works in the way that we first add f and then our string. Variables are embedded inside of curly braces.

fstring is the recommended way to format strings in Python, but if you are working on an older codebase, you might be forced to use .format and %s and hence, it’s good to know them as well.

Lastly, check out Python4Delphi which easily allows you to build Python GUIs for Windows using Delphi!

close
Related posts
DelphiDelphiVCLPythonPython GUIWindows

Learn about the DelphiVCL.Component as the Common Ancestor of All Component Classes

Learn PythonPythonVideos

Learn Python With The Hidden Power of the Python Runtime by Elizaveta Shashkova (PyCon 2020) Videos

Learn PythonPythonVideos

Learn Python With Organizing to Improve Your Workplace: Know Your Rights by Shauna Gordon-McKeon (PyCon 2020) Video

DelphiPythonPython GUIWindows

Learn To Build A Python GUI For Manipulating Datetime Using Delorean Library In A Delphi Windows App

Schreiben Sie einen Kommentar

Ihre E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.

de_DE_formalGerman