String Formatting In Python

In this lesson, we discuss Python string formatting. We will use examples to better serve the needs of the learners in today’s lesson.

The format() method in Python can be used to format a string so that it displays as expected.

Python String Formatting

When you use Python string formatting OR the format() method, you can format selected parts of a string.

Some parts of a text are not under your control. Maybe they come from a database or user input?

You can control such values by adding placeholders curly brackets {} and calling the format() method.

You can display the pi value by inserting a placeholder:

Python String Formatting Example:1 

pi = 3.141592653589793mrx_text = "The value of pi is {:.3f} "print(mrx_text.format(pi))

Python String Formatting example

By inserting a placeholder, you can print the age and height values:

Python String Formatting Example:2 

age = 19 height = 5.742 mrx_text = "Age of Harry is {} and his height is {:.1f} ft" print(mrx_text.format(age,height))

Indicate how to modify the value by including parameters inside the curly brackets.

To display pi as a three-digit number, format the value as follows:

Python String Formatting Example:3 

pi = 3.141592653589793mrx_text = "The value of pi is {:.3f} "print(mrx_text.format(pi))

Show the subjects marks as a number with one decimal place:

Python String Formatting Example:4 

sub_1 = 77.4332 sub_2 = 84.612 mrx_text = "Marks of Harry in first subject is {:.1f} and in second subject is {:.1f}" print(mrx_text.format(sub_1,sub_2))
Visit our Python Strings methods to see all formatting types.


Index Numbers

In order to ensure that the values are placed correctly, you can utilize index numbers (the number within the curly brackets {0}):

Index Numbers Example:1 

processor = "Intel(R) Core(TM) i7" windows = 11 ram = 16.00 mrx_info = "Processor: {0}\nWindows: {1}\nRam: {2:.1f}" print(mrx_info.format(processor, windows, ram))

Index Numbers Example:2 

phone_name = "iPhone 14 Pro Max" os = "IOS 16" cpu = "Hexa-core (2 x 3.46 GHz Avalanche + 4 x Blizzard)" chipset = "Apple A16 Bionic (4 nm)" gpu = "Apple GPU (5-core graphics)" mrx_info = "Phone Name: {0}\nOS: {1}\nCPU: {2}\nChipset: {3}\nGPU: {4}" print(mrx_info.format(phone_name, os, cpu, chipset, gpu))

 

If you need the exact value more than once, apply index number:

Index Numbers Example:3 

name = "Harry" age = 19 player = "football player" mrx = "Name: {0}\n{0} is {1} years old\n{0} lives in the United States of America\n{0} is doing bachelors in computer science\n{0} is also a {2}" print(mrx.format(name, age, player))

Named Indexes

If you want to apply named indexes, include a name inside the curly brackets {name}, but then include names when passing the parameters to txt.format(name = “Elon Musk”):

Named Indexes Example:1 

mrx= "Name: {name}, Age: {age}, Residence: {res}, Net worth: {n_worth}".format(name = "Elon Musk", age = 51, res = "Texas", n_worth = "$128 billion") print(mrx)

Include the following phone specification variables inside curly brackets{} in mrx_info:

Example: 

mrx_info= "Phone Name: {phone_name}\nOS: {os}\nCPU: {cpu}\nChipset: {chipset}\nGPU: {gpu}".format(phone_name = "iPhone 14 Pro Max", os = "IOS 16", cpu = "Hexa-core (2 x 3.46 GHz Avalanche + 4 x Blizzard)", chipset = "Apple A16 Bionic (4 nm)", gpu = "Apple GPU (5-core graphics)")print(mrx_info)

 


Multiple Values

You can pass more values to the format() method if you wish:

print(txt.format(sub_1, sub_2, sub_3, sub_4))

You can also insert more placeholders:

String Format Multiple Value Example:1 

processor = "Intel(R) Core(TM) i7" windows = 11 ram = 16.00 mrx_info = "Processor: {}\nWindows: {}\nRam: {:.1f}" print(mrx_info.format(processor, windows, ram))

String Format Multiple Value Example:2 

phone_name = "iPhone 14 Pro Max" os = "IOS 16" cpu = "Hexa-core (2 x 3.46 GHz Avalanche + 4 x Blizzard)" chipset = "Apple A16 Bionic (4 nm)" gpu = "Apple GPU (5-core graphics)" mrx_info = "Phone Name: {}\nOS: {}\nCPU: {}\nChipset: {}\nGPU: {}" print(mrx_info.format(phone_name, os, cpu, chipset, gpu))

Python String Formatting Advantages

Here are some advantages of using string formatting in Python:

  1. String formatting improves code readability by allowing you to separate the formatting logic from the content of the string. Instead of concatenating strings manually, you can use placeholders or format specifiers to define the structure of the output. This makes the code more concise, easier to understand, and maintainable.
  2. String formatting allows you to dynamically insert values into the output string. You can include variables, expressions, or function calls within the format placeholders. This enables you to generate output that incorporates dynamic data, calculations, or results from other parts of your program.
  3. Python string formatting provides various formatting options to control the appearance of the output. You can specify the width, precision, alignment, padding, and other formatting attributes for numeric values, strings, dates, and more. This allows you to present data in a specific format that meets your requirements.
  4. String formatting supports localization and internationalization efforts. It enables you to format numbers, dates, and currencies according to different regional conventions and language preferences. This flexibility ensures that your program can present output in a way that is culturally appropriate and understandable for different audiences.
  5. By using string formatting, you can create reusable templates with placeholders that can be populated with different values. This allows you to define a template once and reuse it multiple times with different inputs, reducing code duplication and improving code organization.
Your reaction is a vital component of our continuous improvement process, and we are grateful for your input.
We value your feedback.
+1
1
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0

Subscribe To Our Newsletter
Enter your email to receive a weekly round-up of our best posts. Learn more!
icon

Leave a Reply

Your email address will not be published. Required fields are marked *