DEV Community

Cover image for Tip: 2 ways to format a string in Python
Isabelle M.
Isabelle M.

Posted on • Originally published at 30secondsofcode.org

1

Tip: 2 ways to format a string in Python

f-string

Formatted string literals, commonly known as f-strings, are strings prefixed with 'f' or 'F'. These strings can contain replacement fields, enclosed in curly braces ({}).

name = 'John'
age = 32

print(f'{name} is {age} years old') # 'John is 32 years old'
Enter fullscreen mode Exit fullscreen mode

str.format()

The str.format() method works very much alike f-strings, the main difference being that replacement fields are supplied as arguments instead of as part of the string.

name = 'John'
age = 32

print('{0} is {1} years old'.format(name, age)) # 'John is 32 years old'
Enter fullscreen mode Exit fullscreen mode

Do you like short, high-quality code snippets and articles? So do we! Visit 30 seconds of code for more articles like this one or follow us on Twitter for daily JavaScript, React and Python snippets! 👨‍💻

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

While many AI coding tools operate as simple command-response systems, Qodo Gen 1.0 represents the next generation: autonomous, multi-step problem-solving agents that work alongside you.

Read full post →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay