Updated August 5, 2023
Introduction to Python format() Function
Python has acquired a wide and peak level in the market as no language has ever done before, especially in Artificial Intelligence and Data Science. Knowing its methods helps Python developers and Python users work smarter with it. The Python language features a format() function designed to format strings. One way to generate formatted output is by replacing placeholders with actual values. This method is quite flexible. To achieve this, we define a template string and indicate the specific Values that require replacement.
Table of Content
- Introduction to Python format() Function
- Positional and Keyword Arguments
- Formatting Numeric Values
- Formatting Strings
- Formatting Dates and Times
- Advanced Formatting Techniques
- Handling Error Cases and Exceptions
The format() function has two main components:
Template String: You can add specific values to the string. Placeholders are marked by curly braces {} or by positional or named placeholders using the format {index} or {name}.
Values: The data that will fill the placeholders can either be provided as arguments to the format() function or accessed by name if named placeholders are used.
Syntax
format(value,format)
Parameters
- Here value refers to one which needs to be represented.
- python-format() function represents the form in which value has to be presented.
Example
Let’s see a short example for a better understanding.
Country = "United States"
Sport = "Baseball"
message = "The {} famous sport is {}.".format(Country,Sport)
print(message)
Output:
In this example, we use the function format() to insert the values of the variables ‘Country’ and ‘Sport’ into the placeholders {} in the string.
Key Takeaways
- Provide you a brief overview of Python format() Function.
- Each argument is explained in detail with their respective examples.
- You will also learn formatting numeric values, strings, date, time, and additional techniques.
- You will come across specific error cases and exceptions. Knowing how to manage these situations is also a part of this article.
Positional and Keyword Arguments
Python’s format() function supports positional and keyword arguments for string formatting. Understanding how to use these arguments is crucial for effectively utilizing the format() function.
1. Positional Arguments
- Arguments in the format() function are arranged based on their order of appearance in the format string.
- The format string contains placeholder curly braces {} that act as slots for the positional arguments.
- Please make sure to input the positional arguments in the assigned slots in the exact order they are shown.
Code:
City = "New York"
Landmark = "Statue of Liberty"
print("The {} is one of the iconic landmark in {}.".format(Landmark, City))
Output:
2. Keyword Arguments
- When using keyword arguments, you can specify the values of the arguments by their parameter names.
- The format string consists of named placeholders enclosed in curly braces, following the syntax of {parameter_name}.
- When passing keyword arguments to the format() function, use the format of parameter_name=value.
Code:
name = "Bob"
Food = "Burgers"
print("Hi! I am {name} and I love to eat {Food}.".format(name=name, Food=Food))
Output:
3. Mixing Positional and Keyword Arguments
- You can combine positional and keyword arguments in the format() function.
- The processing order for arguments is positional arguments first, followed by keyword arguments.
Code:
City = "New York"
Food = "Burgers"
print("Whenever i visit {0} I always have {Food} its delicious.".format(City, Food=Food))
Output:
Formatting Numeric Values
Python’s format() function provides powerful capabilities for formatting numeric values. You can use it to manage how integers, floating-point numbers, and scientific notation are displayed and set precision, width, and other formatting preferences.
1. Formatting Integers
- You can use format codes to indicate the width and alignment you want to format integers.
- The correct format code for integers is “d”. To align text, use < for left alignment, > for right alignment, and ^ for center alignment.
- You have the option to indicate the width of the field by using a numerical value.
Code:
num = 12
print("My Birthday is on September {:<10d}".format(num))
Output:
2. Formatting Floating-Point Numbers
- You can use format codes that specify precision, width, and alignment to format floating-point numbers.
- To format floating-point numbers, use the code “f”.
- To determine the precision or number of decimal places, use’.’ followed by a number.
- Specify the width and alignment using <, >, or ^.
Code:
num = 4.14159
print("Kindly Print a Float Number: {:.2f}".format(num))
Output:
3. Formatting Scientific Notation
- You can format scientific notation using the “e” format code.
- To specify a precision, use’.’ followed by a number.
- The exponent can be indicated by either “e” or “E” depending on your preferred case.
- You can also specify the width and alignment.
Code:
num = 2.7345e-7
print("Print Formatted scientific notation: {:.2e}".format(num))
Output:
4. Format() for signed numbers
- Usually, sign indicators are not present in positive numbers, while negative numbers have a minus sign (-) before them.
- You have the option to indicate the sign character by using the + or – format codes.
Code:
print("{:+f} {:+f}".format(21.99, -22.99)) # This will show the + sign
print("{:-f} {:-f}".format(21.99, -22.99)) # This will show the - sign only
Output:
Formatting Strings
The format() function in Python offers a range of options to format and manipulate strings. Using the format() function, you can align and justify strings, manipulate capitalization and letter case, and add padding and truncation. Take a look at this overview of the string formatting options available.
1. Aligning and Justifying Strings
- To align strings within a particular width, you can use the format codes < for left-aligning, > for right-aligning, and ^ for center-aligning.
- By default, strings are left-aligned.
Code:
print("{:6}".format("dog")) # string-padding with left-alignment
print("{:>6}".format("dog")) # string-padding with right-alignment
print("{:^7}".format("dog")) # string-padding with center-alignment
Output:
As one notices here:
- Case 1: {:6} occupied 6 spaces, and the dog will be printed from the left. The remaining 3spaces will be just occupied.
- Case 2: {:>6} occupied 6 spaces, but the dog is finally printed. The front 3 places will remain blank.
- Case 3: {:^7} occupies 7 spaces, and the dog will be printed with center alignment.
2. Formatting with padding
Padding refers to adding spaces to the right or left of the text/numeral.
Code:
print("{:6d}".format(12))
Output:
Here to print “12”, it’s been padded with 6d. That means 4 spaces, and then the digit gets displayed(as shown above). As alignment has not been specified, it’s aligned to the right by default. However, if you want to show spaces with zero, you can place 0 before the format specifier.
3. Truncate String using format()
Truncation refers to shortening a string by removing characters from its end to limit its length.
Code:
print("{:.5}".format("Singapore"))
print("{:^7.3}".format("Singapore"))# truncating strings to 3 letters, and then padding & center-aligned
Output:
- Case 1: Here {:.5} will truncate a string to the first five characters. Hence “Singapore” will come down to “Singa”.
- Case 2: It’s a combination of truncation and alignment. First, “Singapore” will be truncated to 3 characters, i.e., “Sin”, and then ^7 will help you center align “Sin” with the occupation of 7 spaces.
4. Controlling Letter Case
- You can utilize format codes to modify the letter case and capitalize strings.
- The function “upper()” transforms all characters to uppercase.
- The lower() function converts all characters to lowercase.
- The capitalize() function capitalizes the first character of a string.
Code:
text = "Educba"
print("Uppercase: {:s}".format(text.upper()))
print("Lowercase: {:s}".format(text.lower()))
print("Capitalized: {:s}".format(text.capitalize()))
Output:
5. Reusing Arguments in Strings
- You can refer to it using its positional index to use the same argument multiple times in a format string.
- Use the positional index and {} to indicate which argument to reuse.
Code:
Word = "Try"
print(" {0} {0} till you succeed!".format(Word))
Output:
Formatting Dates and Times
In Python, the format() function can format dates and times. This allows you to personalize how date and time objects are displayed. You can use format codes to display dates and times accurately in different regions. Here is an overview of how to format dates and times using this function:
1. Formatting Date and Time Objects
- When formatting date and time objects, you can use format codes to represent different components such as year, month, day, hour, minute, and second.
- Some common format codes used are %Y for the year in four-digit format, %m for a zero-padded month, %d for a zero-padded day, %H for a zero-padded hour in 24-hour format, %M for a zero-padded minute, and %S for a zero-padded second.
- You can use separators and other characters along with these format codes to achieve the desired date and time format.
Code:
import datetime
current_datetime = datetime.datetime.now()
formatted_datetime = current_datetime.strftime("%Y-%m-%d %H:%M:%S")
print(formatted_datetime)
Output:
2. Specifying Custom Date and Time Formats
- You can combine format codes with the desired separators and characters to create custom date and time formats.
- One way to format dates and times is by using different codes. For instance, %b stands for the abbreviated month name, %B for the full month name, %d for zero-padded day, %Y represents the four-digit year, and %I denotes zero-padded hour in 12-hour format.
Code:
import datetime
current_datetime = datetime.datetime.now()
formatted_datetime = current_datetime.strftime("%b %d, %Y - %I:%M %p")
print(formatted_datetime)
Output:
3. Displaying Localized Date and Time
- Using the locale module, the function format() can handle localized date and time representations.
- To set the preferred locale, utilize the function locale.setlocale(). Then, you can format date and time objects by implementing the %x and %X format codes.
Code:
import datetime
import locale
locale.setlocale(locale.LC_ALL, "en_US.UTF-8")
current_datetime = datetime.datetime.now()
formatted_date = current_datetime.strftime("%x")
formatted_time = current_datetime.strftime("%X")
print("Today's Date:", formatted_date)
print("Current Time:", formatted_time)
Output:
Advanced Formatting Techniques
Python’s format() function allows for more advanced techniques beyond basic string formatting. One can employ dynamic format strings and conditional formatting techniques using dictionaries and named placeholders. Here’s an overview of these advanced formatting techniques:
Code:
data = {"Word": "Season", "Data": "Monsoon"}
formatted_string = "My favourite {Word} is {Data}.".format(**data)
print(formatted_string)
Output:
1. Creating Dynamic Format Strings
- You can create dynamic format strings by using variables or expressions as the format string.
- The format string can be created according to different conditions, calculations, or dynamic factors.
Code:
is_uppercase = True
format_string = "{name}" if is_uppercase else "{name.lower()}"
formatted_string = format_string.format(name="Educba")
print(formatted_string)
Output:
2. Applying Conditional Formatting
- You can include conditional statements or expressions in the format string to apply conditional formatting.
- Conditional statements allow for formatting to be determined based on specific conditions.
Code:
age = 25
formatted_string = "You are {}.".format("an adult" if age >= 18 else "a minor")
print(formatted_string)
Output:
Handling Error Cases and Exceptions
In Python, when utilizing the format() function, it’s possible to come across specific error cases and exceptions. Knowing how to manage these situations is crucial for ensuring strong and accurate string formatting. When utilizing format(), it’s important to take into account how to handle error cases and exceptions.
1. Missing Arguments
- If there are fewer arguments for the placeholders in the format string, an IndexError will be raised.
- To tackle this issue, you have two options. Firstly, you can provide default values for the arguments, or secondly, you can use conditional checks to ensure that all the necessary arguments are present.
Code:
Country = "Italy"
formatted_string = "Hello, {}. Today is {}.".format(Country) # Missing the second argument
print(formatted_string)
Output:
If there is an error with a missing argument, there are two options to fix it. You can either give a default value for the missing argument or adjust the format string to include all necessary placeholders.
2. Key Errors
- In cases where the format string utilizes named placeholders but the given arguments do not have a necessary key, it will result in a raised KeyError.
- One way to address this error is to implement dictionaries with default values or utilize exception handling to catch the KeyError.
Code:
data = {"name": "Alice"}
formatted_string = "Hello, {name}. Age: {age}.".format(**data) # Missing the 'age' key
print(formatted_string)
Output:
There are two solutions if you encounter an error with a missing key. You can either set a default value for the missing key or use exception handling to catch the KeyError.
3. Format Errors
- The format string’s incorrect syntax or invalid format codes will raise a ValueError.
- To address this error, double-check the construction of the format string and verify the use of format codes to ensure their accuracy.
Code:
name = "Alice"
age = 25
formatted_string = "Hello, {}. Today is {date:%Y-%m-%d}.".format(name)
print(formatted_string)
except ValueError as e:
print("ValueError:", e)
Output:
Follow the correct syntax and format codes to avoid format errors
4. Exception Handling
- It’s advisable to incorporate exception handling when utilizing the format() function to capture and manage any probable errors.
- One can implement a try-except block to handle particular exceptions like IndexError, KeyError, or ValueError, and come up with suitable error handling or fallback plans.
Code:
try:
name = "Alice"
formatted_string = "Hello, {}. Today is {}.".format(name)
print(formatted_string)
except IndexError:
print("Error: Insufficient arguments provided.")
except KeyError:
print("Error: Missing required key in arguments.")
except ValueError:
print("Error: Invalid format string.")
Output:
With exception handling, you can manage errors and exceptions that might arise while formatting strings more refinedly. This enables you to present informative error messages or alternative approaches to ensure your program runs smoothly.
To ensure the reliability of your string formatting operations and avoid unexpected errors, it is essential to anticipate and handle error cases appropriately while working with the format() function.
FAQs
Q1: Are there any limitations to string truncation using format()?
Answer: There is no direct string truncation capability in the format() function. However, you can use string slicing or conditional checks to limit the length of the string and achieve truncation.
Q2: Can I apply formatting to localized dates and times?
Answer: Yes, the locale module can display localized date and time representations in Python. Set your preferred locale with locale.setlocale() and format the date and time objects using the %x and %X format codes.
Q3: How can I handle format errors when using format()?
Answer: A value error may occur if there are code or syntax formatting issues. To avoid this, it is essential to thoroughly check and verify the format string for correct syntax and valid format codes.
Conclusion
As we have seen above, how to format functions and formatting operators are important in formatting the variables to a specific type in Python. There are ample approaches available to format variables; one should be aware of the cases, which suits were, as per scenario. By providing a template string and the values, you can create well-formatted output for various purposes.
Recommended Articles
We hope that this EDUCBA information on “Python format() Function” was beneficial to you. You can view EDUCBA’s recommended articles for more information.