For working professionals
For fresh graduates
More
13. Print In Python
15. Python for Loop
19. Break in Python
23. Float in Python
25. List in Python
27. Tuples in Python
29. Set in Python
53. Python Modules
57. Python Packages
59. Class in Python
61. Object in Python
73. JSON Python
79. Python Threading
84. Map in Python
85. Filter in Python
86. Eval in Python
96. Sort in Python
101. Datetime Python
103. 2D Array in Python
104. Abs in Python
105. Advantages of Python
107. Append in Python
110. Assert in Python
113. Bool in Python
115. chr in Python
118. Count in python
119. Counter in Python
121. Datetime in Python
122. Extend in Python
123. F-string in Python
125. Format in Python
131. Index in Python
132. Interface in Python
134. Isalpha in Python
136. Iterator in Python
137. Join in Python
140. Literals in Python
141. Matplotlib
144. Modulus in Python
147. OpenCV Python
149. ord in Python
150. Palindrome in Python
151. Pass in Python
156. Python Arrays
158. Python Frameworks
160. Python IDE
164. Python PIP
165. Python Seaborn
166. Python Slicing
168. Queue in Python
169. Replace in Python
173. Stack in Python
174. scikit-learn
175. Selenium with Python
176. Self in Python
177. Sleep in Python
179. Split in Python
184. Strip in Python
185. Subprocess in Python
186. Substring in Python
195. What is Pygame
197. XOR in Python
198. Yield in Python
199. Zip in Python
In Python programming, working with strings is inevitable. Whether you're creating user messages, generating reports, or simply displaying values, strings are everywhere. But printing plain strings isn’t enough—you often need to dynamically insert variables, format numbers, or control alignment. That’s where string formatting steps in.
String formatting in Python gives you the power to present your output exactly the way you want it. Python offers multiple ways to do this—from the traditional % operator to the modern and efficient f-strings. This article walks you through all these methods, shows where and how to use each one, and helps you avoid common pitfalls. By the end, you’ll know exactly which formatting style fits best for your needs—whether you're a college student debugging assignments or a school student printing your first “Hello, World!” output. Pursue our Software Engineering courses to get hands-on experience!
String formatting in Python is a way to insert variables, expressions, or values into strings while maintaining readability and structure. Instead of manually breaking strings or using commas in print() statements, you use formatting techniques to embed values directly where they belong.
In simpler terms, it lets you say: “Hey Python, place this value here, and that one there, all neat and clean.” This comes in handy when you want your output to be user-friendly or professional, especially when displaying numbers, dates, or combining strings with data.
Example:
name = "Rajat"
age = 20
print("My name is {} and I am {} years old.".format(name, age))
Output:
My name is Rajat and I am 20 years old.
Explanation: Here, {} placeholders are used inside the string, and the format() method injects the values of name and age in order. This avoids messy concatenation and gives a cleaner, structured result.
Advance your skill set with these carefully curated programs.
Tip: If you’re dealing with user input or dynamically changing values, string formatting helps keep your output predictable and organized.
String formatting is essential because it helps you present data clearly and efficiently. When you print variables or combine different data types in Python, just putting them side by side can lead to messy or unreadable output. Formatting ensures the output is clean, readable, and professional.
For example, if you want to show a user’s score with a message, you need the number and text to appear together seamlessly. Without formatting, this can get complicated, especially when dealing with decimals, dates, or multiple variables.
Moreover, string formatting allows you to control how data appears. You can specify the number of decimal places, align text, pad numbers with zeros, and much more. This is especially helpful in assignments, projects, or presentations where polished output makes a difference.
In short, string formatting transforms raw data into meaningful, well-structured information—making your programs more user-friendly and easier to debug.
The % operator is one of the oldest methods for string formatting in Python. It works similarly to the C language’s printf style formatting. You use % as a placeholder in the string, followed by a format specifier that tells Python what type of data to insert.
Example:
name = "Anjali"
marks = 85
print("Student %s scored %d marks." % (name, marks))
Output:
Student Anjali scored 85 marks.
Explanation: The %s is replaced by the string name, and %d is replaced by the integer marks. Values are provided in a tuple after the % operator.
You can also control decimal precision by specifying it like %.2f, which formats the number to 2 decimal places.
price = 99.4567
print("Price: %.2f" % price)
Output:
Price: 99.46
Important Note:-
While the % operator is still widely used, newer methods like str.format() and f-strings are more flexible and recommended for modern Python code.
The str.format() method is a more powerful and flexible way to format strings in Python. It uses curly braces {} as placeholders in the string, which are replaced by values passed as arguments to the format() function.
Example:
name = "Swastik"
score = 92
print("Hello, {}! Your score is {}.".format(name, score))
Output:
Hello, Swastik! Your score is 92.
Explanation: The {} placeholders are replaced by the values of name and score in the order they appear in the format() method.
You can specify the order explicitly using numbers inside the braces:
print("Score of {1} is {0}".format(score, name))
Output:
Score of Swastik is 92
Or use keyword arguments for better clarity:
print("Name: {student}, Marks: {marks}".format(student=name, marks=score))
Output:
Name: Swastik, Marks: 92
You can format numbers for alignment and precision:
pi = 3.14159
print("Value of pi: {:.2f}".format(pi))
Output:
Value of pi: 3.14
Advantages of str.format():
f-strings, officially called formatted string literals, were introduced in Python 3.6 as a modern and efficient way to format strings. They allow you to embed Python expressions directly inside string literals by prefixing the string with the letter f and placing expressions within curly braces {}.
This makes the code much cleaner and easier to read compared to older methods. Instead of using separate .format() calls or % operators, you write the variables right where you want them in the string. This reduces boilerplate code and improves maintainability.
name = "Priya"
age = 22
print(f"My name is {name} and I am {age} years old.")
Output:
My name is Priya and I am 22 years old.
Here, the variables name and age are directly inserted into the string, improving clarity and reducing errors.
Example:
print(f"Next year, I will be {age + 1} years old.")
Output:
Next year, I will be 23 years old.
If you are using Python 3.6 or later, f-strings are the recommended choice for string formatting. They promote readable, concise, and efficient code. However, if you need to support older Python versions, you should use str.format() instead.
Even though Python’s string formatting is straightforward, beginners often stumble over a few common mistakes. Knowing these will save you time and frustration.
1. Mismatching Placeholders and Values
When using % or format(), the number of placeholders {} or % specifiers must match the number of values supplied.
# Incorrect:
print("Name: %s, Age: %d" % ("Rajat")) # Only one value for two placeholders
# Correct:
print("Name: %s, Age: %d" % ("Rajat", 21))
Explanation: The first example throws a TypeError because Python expects two values but receives one.
2. Forgetting to Prefix f-strings with f
A common error is writing an f-string without the f prefix, turning it into a normal string.
name = "Anjali"
print("Hello, {name}!") # Prints literally: Hello, {name}!
print(f"Hello, {name}!") # Correct usage; outputs: Hello, Anjali!
3. Using Unsupported Formatting in Older Python Versions
f-strings only work in Python 3.6+. Using them in older versions will cause syntax errors.
4. Mixing Different Formatting Styles
It’s best to stick to one formatting method in your code for readability and consistency.
# Avoid mixing:
print("Hello %s" % "Rajat")
print("Hello {}".format("Rajat"))
print(f"Hello {'Rajat'}")
5. Not Handling Special Characters Properly
If your string includes curly braces {} and you’re using format(), you need to escape them by doubling:
print("This is a brace: {{}}".format())
Output:
This is a brace: {}
Mastering string formatting can make your code cleaner, faster, and more maintainable. Here are some practical tips and best practices to keep in mind:
1. Prefer f-strings for Modern Python Projects
If you’re using Python 3.6 or later, always choose f-strings. They are more readable and perform better than older methods.
2. Use Named Placeholders for Clarity
With str.format(), use named placeholders to make your code easier to understand.
print("Name: {name}, Age: {age}".format(name="Sarthak", age=25))
3. Control Number Formatting Precisely
To format numbers with specific decimal places or padding, use format specifiers inside placeholders.
value = 7.12345
print(f"Value rounded to 2 decimals: {value:.2f}")
4. Align Text for Better Output Presentation
You can left-align, right-align, or center text within a fixed width for cleaner reports.
print(f"|{'Name':<10}|{'Score':>5}|")
print(f"|{'Priya':<10}|{95:>5}|")
5. Escape Curly Braces When Needed
If you want to display { or } in your output, double them in your format string.
print(f"Use {{}} to represent braces in f-strings.")
6. Avoid Overcomplicating Format Strings
Keep format strings simple and readable. If your expression gets too long, consider breaking it into variables.
7. Use Formatting Consistently in Your Project
Choose one style of string formatting and stick to it for consistency, which improves code readability and maintenance.
With these tips, your string formatting will be clean, professional, and easy to manage—ideal for both assignments and real-world projects. Access a comprehensive Python cheat sheet for quick reference.
String formatting is a fundamental skill that every Python programmer should master. It not only helps you display data clearly but also adds professionalism to your programs. Whether you choose the classic % operator, the versatile str.format() method, or the modern f-strings, understanding each method’s strengths lets you write cleaner and more efficient code.
As Python continues to evolve, f-strings are becoming the preferred choice due to their simplicity and performance. However, knowing multiple methods gives you flexibility, especially when working with legacy code or different Python versions.
Keep practicing string formatting with real examples, and soon it will become second nature. Remember, clear and well-formatted output is not just about looks—it makes your code easier to debug, maintain, and share.
String formatting in Python inserts variables into strings using placeholders. It helps present data clearly without messy concatenations. This improves readability and makes output more professional and easier to maintain in programs.
Yes, Python supports formatting numbers and dates. You can control decimal places, add padding, and format dates using format specifiers. This ensures the output is clean and suits your needs, especially for reports or user interfaces.
f-strings embed expressions directly inside string literals with an f prefix, making them concise and faster. The str.format() method is more flexible, supports older Python versions, and allows positional and keyword arguments.
For Python 3.6 and above, f-strings are best due to clarity and speed. For earlier versions, str.format() is preferred. The % operator is considered outdated but still functional for simple cases.
Yes, dictionaries and lists can be used with str.format() or f-strings. You access values by keys or indices, allowing dynamic string creation from complex data structures conveniently.
Use format specifiers like < (left), > (right), or ^ (center) with a width inside placeholders. This helps align text neatly in reports or tables for better readability.
Python raises an error if the number of placeholders differs from the values provided. Always ensure they match exactly to prevent runtime exceptions and program crashes during string formatting.
Yes, f-strings allow inline expressions like calculations or function calls within braces {}. This flexibility lets you format dynamic data directly in the string without extra variables or steps.
To print curly braces {} literally, double them as {{ and }} in both str.format() and f-strings. This escaping prevents Python from treating them as placeholders during string formatting.
Definitely. String formatting displays user input cleanly, allowing control over how data appears. It helps in validation, preventing errors, and creating professional-looking messages or reports involving user data.
Use .2f format specifier inside placeholders, like f"{value:.2f}". This rounds the floating number to two decimal places, improving the appearance and precision of numeric outputs.
Yes, f-strings are generally the fastest as they are evaluated at runtime. The % operator and str.format() are slower but still widely supported, making f-strings the preferred choice for performance.
Yes, you can use placeholders within triple-quoted strings for multi-line formatting. This allows inserting variables or expressions into strings spanning several lines, useful for formatted reports or messages.
For Python versions before 3.6, use the % operator or the str.format() method, as f-strings are not supported. Both are reliable ways to format strings in older environments.
Avoid mismatched placeholders and values, forgetting the f prefix for f-strings, mixing formatting styles, and failing to escape curly braces. These prevent common errors and improve code readability.
Take our Free Quiz on Python
Answer quick questions and assess your Python knowledge
Author|900 articles published
Previous
Next
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918068792934
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.