Golang Tutorials - Learn Go Programming with Easy Step-by-Step Guides

Explore comprehensive Golang tutorials for beginners and advanced programmers. Learn Go programming with easy-to-follow, step-by-step guides, examples, and practical tips to master Go language quickly.

String Formatting in Python

String Formatting in Python

String Formatting in Python

String formatting in Python allows you to construct strings in a readable, flexible, and efficient manner. It allows you to embed expressions inside string literals and perform operations on them.

There are several methods of string formatting in Python, including:

  1. Using % operator (Old Style)

  2. Using .format() method (New Style)

  3. Using f-strings (Formatted String Literals) (Python 3.6 and above)


1. String Formatting with the % Operator (Old Style)

This is the old style of string formatting, using the % operator. You can use placeholders like %s for strings, %d for integers, and %f for floats, among others.

Syntax:

"string % (values)"

Example:

name = "Alice"age = 25formatted_string = "My name is %s and I am %d years old." % (name, age)print(formatted_string)# Output: My name is Alice and I am 25 years old.

Common Format Specifiers:

  • %s: String (or any object with __str__() method).

  • %d: Integer.

  • %f: Float (decimal point).

  • %.2f: Float with two decimal points.


2. String Formatting with .format() Method (New Style)

The .format() method is more powerful and flexible than the % operator and is part of Python 3.x. This method allows you to use curly braces {} as placeholders and insert variables by passing them to the format() function.

Syntax:

"string {}".format(values)

Example:

name = "Alice"age = 25formatted_string = "My name is {} and I am {} years old.".format(name, age)print(formatted_string)# Output: My name is Alice and I am 25 years old.

Positional and Keyword Arguments:

You can specify arguments in any order using either positional or keyword arguments.

# Positional argumentsformatted_string = "My name is {0} and I am {1} years old.".format(name, age)print(formatted_string)  # Output: My name is Alice and I am 25 years old.# Keyword argumentsformatted_string = "My name is {name} and I am {age} years old.".format(name=name, age=age)print(formatted_string)  # Output: My name is Alice and I am 25 years old.

Formatting Numbers:

You can also specify how numbers are formatted, e.g., limiting decimal points or formatting them with commas.

# Formatting float to 2 decimal placespi = 3.14159formatted_string = "The value of pi is {:.2f}".format(pi)print(formatted_string)  # Output: The value of pi is 3.14# Using commas in large numberslarge_number = 1000000formatted_string = "The number is {:,}".format(large_number)print(formatted_string)  # Output: The number is 1,000,000

3. String Formatting with f-Strings (Formatted String Literals)

Introduced in Python 3.6, f-strings (formatted string literals) offer a concise and readable way to embed expressions inside string literals. You prefix the string with an f and use curly braces {} to embed variables or expressions directly.

Syntax:

f"string {expression}"

Example:

name = "Alice"age = 25formatted_string = f"My name is {name} and I am {age} years old."print(formatted_string)# Output: My name is Alice and I am 25 years old.

Evaluating Expressions Inside f-Strings:

You can also perform operations or evaluate expressions inside the curly braces.

x = 5y = 10formatted_string = f"Sum of {x} and {y} is {x + y}"print(formatted_string)  # Output: Sum of 5 and 10 is 15

Formatting Numbers:

Like with .format(), you can also control the formatting of numbers in f-strings.

pi = 3.14159formatted_string = f"The value of pi is {pi:.2f}"print(formatted_string)  # Output: The value of pi is 3.14

Using f-strings with Dictionaries:

You can also use variables from dictionaries or objects within f-strings.

person = {'name': 'Alice', 'age': 25}formatted_string = f"My name is {person['name']} and I am {person['age']} years old."print(formatted_string)  # Output: My name is Alice and I am 25 years old.

Comparison of Methods

Feature% Operator.format() Methodf-Strings (Python 3.6+)
Syntax"string % (values)""string {}".format(values)f"string {expression}"
ReadabilityLess readableMore readableMost readable and concise
FlexibilityLess flexibleMore flexibleVery flexible
Expressions insideNot supportedSupportedSupported (most flexible)
Performance (for large data)SlowerSlower than f-stringsFastest

Conclusion

  • % operator: This is the old way of string formatting and is still useful for simple cases but is less flexible and readable than the newer methods.

  • .format() method: A more modern and versatile approach, allowing positional, keyword arguments, and more complex formatting.

  • f-strings: The most preferred way in Python 3.6+ due to their readability, ease of use, and performance.

If you're using Python 3.6 or later, f-strings are generally the recommended choice for string formatting due to their clarity and efficiency.

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql