What’s New ?

The Top 10 favtutor Features You Might Have Overlooked

Read More

Python String Formatting (With Codes)

  • Nov 09, 2023
  • 7 Minutes Read
  • Why Trust Us
    We uphold a strict editorial policy that emphasizes factual accuracy, relevance, and impartiality. Our content is crafted by top technical writers with deep knowledge in the fields of computer science and data science, ensuring each piece is meticulously reviewed by a team of seasoned editors to guarantee compliance with the highest standards in educational content creation and publishing.
  • By Abhisek Ganguly
Python String Formatting (With Codes)

String formatting is a fundamental skill in Python programming, as it enables you to craft and manipulate strings, enhancing their informativeness, visual appeal, and adaptability to diverse contexts. In the following article, we will embark on an in-depth exploration of Python string formatting. This journey will encompass various techniques, practical examples, and best practices.

What is Python String Formatting?

String formatting indeed involves the creation of a string that contains placeholders for data, followed by the substitution of those placeholders with actual values. Python offers several methods for achieving string formatting, and your choice of method should be based on your particular requirements and coding style. This flexibility in string formatting allows you to tailor your approach to the specific context and readability of your code.

String Formatting Methods

Let's now learn about the different formatting methods in strings.

1. Old-Style Formatting

Old-style formatting, often referred to as "printf-style" formatting, relies on the % operator to format strings. This method has been largely replaced by more modern string formatting techniques in Python but is still supported for compatibility with legacy code and for those who are accustomed to it. While it's considered less readable and flexible compared to the newer methods, it remains a viable option for some situations. However, it's important to note that the newer string formatting methods, such as f-strings and str.format(), are generally recommended for new Python code.

Code:

name = "Joseph"
age = 30
formatted_string = "Name: %s, Age: %d" % (name, age)
print(formatted_string)

 

Output:

Name: Joseph, Age: 30

2. String Interpolation

String interpolation is a more modern approach, introduced in Python 3.6, that uses f-strings. It allows you to embed expressions directly in string literals using curly braces {}.

Code:

name = "David"
age = 25
formatted_string = f"Name: {name}, Age: {age}"
print(formatted_string)

 

Output:

Name: David, Age: 25

 

3. f-strings (Formatted String Literals)

F-strings are a powerful and convenient way to format strings, offering excellent readability and flexibility. They are created by prefixing a string with 'f' or 'F' and can contain expressions inside curly braces.

Code:

name = "James"
age = 25
formatted_string = f"Name: {name}, Age: {age}"
print(formatted_string)

 

Output:

Name: James, Age: 25

 

4. str.format() Method

The str.format() method provides another method for string formatting. It allows you to define placeholders within a string and then populate them with values provided as arguments to the format method.

Code:

name = "Mary"
age = 40
formatted_string = "Name: {}, Age: {}".format(name, age)
print(formatted_string)

 

Output:

Name: Mary, Age: 40

 

5. Template Strings

Template strings are a less commonly used method but provide a simple way to substitute variables within strings using a dollar sign and curly braces.

Code:

from string import Template
name = "Eve"
age = 45
formatted_string = Template("Name: $name, Age: $age").substitute(name=name, age=age)
print(formatted_string)

 

Output:

Name: Eve, Age: 45

 

Common String Formatting Operations

Here are a few different techniques to implement string formatting operations in Python programming language. Each type serves a specific purpose and can be used in different kinds of scenarios as per our requirements.

1. String Alignment

String formatting allows you to align text within a fixed-width field, making it visually appealing. For example, you can left-align, right-align, or center-align text within a specified width.

Code:

text = "Hello"
left_aligned = f"{text:<10}"
right_aligned = f"{text:>10}"
center_aligned = f"{text:^10}"
print(left_aligned, right_aligned, center_aligned)

 

Output:

Hello     Hello Hello     

 

2. Number Formatting

When working with numeric data, you can format numbers with specific precision, alignment, and thousands of separators.

Code:

number = 12345.6789
formatted_number = f"{number:,.2f}"
print(formatted_number)

 

Output:

12,345.68

 

3. Date and Time Formatting

String formatting is essential for working with date and time data, allowing you to convert timestamps into human-readable formats.

Code:

from datetime import datetime
now = datetime.now()
formatted_time = now.strftime("%Y-%m-%d %H:%M:%S")
print(formatted_time)

 

Output:

2023-11-09 12:34:56  # The actual date and time will vary

 

4. Custom Formatting

You can define custom formatting for your own data types by creating custom string format specifiers. This gives you complete control over how objects are represented as strings.

Performance Considerations

String formatting's impact on performance becomes particularly pronounced when dealing with extensive datasets. It is crucial to bear in mind the significance of performance considerations when selecting a formatting method. As you navigate through Python string formatting, especially with large volumes of data, it is essential to weigh the performance implications of your chosen formatting method.

Thoughtful consideration of the efficiency of these methods not only optimizes code execution speed but also contributes to the overall responsiveness and scalability of your Python applications. Thus, a prudent examination of the performance characteristics associated with different string formatting techniques is vital for maintaining code integrity and ensuring robust performance in the face of diverse computational challenges.

1. Concatenation vs. Joining

In the domain of string manipulation, the decision-making process between fundamental techniques such as string concatenation or joining and more intricate approaches assumes paramount significance, particularly when contending with expansive datasets. There exists a pragmatic consideration that, in certain scenarios, the simplicity and straightforwardness of employing basic string concatenation or joining methods may outshine the performance of advanced string formatting techniques. This is especially noticeable when dealing with large datasets, where the streamlined process of combining strings through direct concatenation proves to be more optimized in terms of computational resources. Developers must discern the nuanced intricacies of their specific use case and weigh the benefits of performance against the added complexity introduced by advanced string formatting methods.

2. String Formatting Performance

Python's extensive library of string formatting methods reveals a wide range of alternatives, each with its own set of advantages and disadvantages. The performance of various methodologies can vary depending on the use case, needing a methodical approach to evaluation. In this regard, profiling and benchmarking emerge as invaluable tools, allowing for granular investigation of the execution speed and efficiency of various formatting methods under varied conditions. Developers can determine the ideal method customised to the complexities of their specific situation by engaging in careful profiling and benchmarking practises. This provides not only efficient string handling, but also a codebase that has been fine-tuned for performance and responsiveness.

Conclusion

Python offers a variety of powerful and flexible methods for string formatting, catering to different needs and preferences. Understanding these methods, their strengths and their performance characteristics will enable you to make informed decisions when working with strings in Python. In this article, we explored Python string formatting in-depth, covering old-style formatting, string interpolation, f-strings, str.format(), and template strings. We also discussed common string formatting operations and considerations for optimizing performance. 

FavTutor - 24x7 Live Coding Help from Expert Tutors!

About The Author
Abhisek Ganguly
Passionate machine learning enthusiast with a deep love for computer science, dedicated to pushing the boundaries of AI through academic research and sharing knowledge through teaching.