Fundamentals 2 min read

Master Python String Formatting: From Basics to Practical Examples

This article introduces Python's string formatting operators, explains how %r converts values to strings and %d formats integers, and demonstrates their usage with concrete code examples and output, guiding beginners through building formatted messages step by step.

AI Large-Model Wave and Transformation Guide
AI Large-Model Wave and Transformation Guide
AI Large-Model Wave and Transformation Guide
Master Python String Formatting: From Basics to Practical Examples

Although strings have been introduced earlier, this section explores more complex string variables and their practical uses.

In Python, formatted strings allow conversion of values into specific textual representations using format specifiers such as %r (convert to string representation) and %d (convert to decimal integer).

Only these two specifiers are covered here; readers can search "Python formatted string" for additional options.

Example usage:

a = "There are %d apples" % 10  # single argument
b = "hey"
c = "hello"
d = "say %r means % r" % (b, c)  # two arguments
print(a)
print(d)

The script prints the formatted messages, and the resulting output is shown below:

Formatted string output
Formatted string output
PythontutorialProgramming FundamentalsbasicsString Formatting
AI Large-Model Wave and Transformation Guide
Written by

AI Large-Model Wave and Transformation Guide

Focuses on the latest large-model trends, applications, technical architectures, and related information.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.