Quantcast
Channel: Planet Python
Viewing all articles
Browse latest Browse all 23384

Python Morsels: String Formatting Techniques

$
0
0

Python's string formatting syntax is both powerful and complex. Let's break it down and then look at some cheat sheets.

What are we talking about?

Python's string formatting syntax allows us to inject objects (often other strings) into our strings.

>>> name="Trey">>> print(f"My name is {name}. What's your name?")My name is Trey. What's your name?
>>> name="Trey">>> print(f"My name is {name}. What's your name?")My name is Trey. What's your name?

We can even embed expressions:

>>> name="Trey">>> print(f"{name}, which starts with {name[0]}")Trey, which starts with T
>>> name="Trey">>> print(f"{name}, which starts with {name[0]}")Trey, which starts with T

But Python's string formatting syntax also allows us to control the formatting of each of these string components.

There is a lot of complexity in Python's string formatting syntax. If you're just for quick answers, skip to the cheat sheets section.

Definitions

Let's start with some definitions. …

Read the full article: https://www.pythonmorsels.com/string-formatting/


Viewing all articles
Browse latest Browse all 23384

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>