Python Tutorial

Python Flow Control

Python Functions

Python Data Types

Python Date and Time

Python Files

Python String

Python List

Python Dictionary

Python Variable

Python Input/Output

Python Exceptions

Python Advanced

String Formatting in Python

In Python, you can use various methods to format and convert strings, such as concatenation, interpolation, and the format() function. This response will focus on string interpolation and the format() function, as they are more versatile and commonly used.

  • String interpolation (f-strings)

In Python 3.6 and later, you can use f-strings (formatted string literals) to embed expressions inside string literals. To create an f-string, prefix the string with an f or F and enclose expressions within curly braces {}.

Example:

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

You can also include format specifiers to control the presentation of the values. For example:

pi = 3.14159265
print(f"Pi rounded to 3 decimal places: {pi:.3f}")
# Output: Pi rounded to 3 decimal places: 3.142
  • format() function

The format() function allows you to format strings using placeholders within the string, which are defined by curly braces {}.

Example:

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

You can use positional and keyword arguments to specify the order in which values should be formatted:

print("{1} is {0} years old.".format(age, name))
# Output: John is 30 years old.
print("{name} is {age} years old.".format(name="John", age=30))
# Output: John is 30 years old.

Additionally, you can include format specifiers to control the presentation of the values:

pi = 3.14159265
print("Pi rounded to 3 decimal places: {:.3f}".format(pi))
# Output: Pi rounded to 3 decimal places: 3.142

In conclusion, Python provides various methods to format and convert strings. F-strings and the format() function are commonly used for their versatility and readability.

  1. Formatting strings with placeholders in Python:

    • Description: Placeholders like %s and %d can be used in strings to insert values.
    • Example Code:
      name = "Alice"
      age = 30
      formatted_string = "My name is %s, and I am %d years old." % (name, age)
      
  2. Using the format() method in Python strings:

    • Description: The .format() method allows for more flexibility and readability in string formatting.
    • Example Code:
      name = "Bob"
      age = 25
      formatted_string = "Hello, my name is {} and I am {} years old.".format(name, age)
      
  3. F-strings in Python for string interpolation:

    • Description: F-strings (formatted string literals) provide a concise way for string interpolation in Python.
    • Example Code:
      name = "Charlie"
      age = 22
      f_string = f"Name: {name}, Age: {age}"
      
  4. String formatting with positional arguments in Python:

    • Description: Positional arguments in the .format() method allow specifying the order of values.
    • Example Code:
      item = "Book"
      price = 19.99
      formatted_string = "Item: {0}, Price: ${1:.2f}".format(item, price)
      
  5. Named placeholders and keyword arguments in Python format strings:

    • Description: Named placeholders and keyword arguments in the .format() method provide clarity and order independence.
    • Example Code:
      item = "Laptop"
      price = 999.99
      formatted_string = "Item: {product}, Price: ${amount:.2f}".format(product=item, amount=price)
      
  6. Formatting numbers and decimals in Python strings:

    • Description: Format specifiers control the display of numbers and decimals within strings.
    • Example Code:
      value = 123.456789
      formatted_value = "Formatted value: {:.2f}".format(value)
      
  7. String alignment and padding in Python formatting:

    • Description: Adjust the alignment and padding of strings using format options.
    • Example Code:
      message = "Hello"
      formatted_message = "{:^20}".format(message)  # Centered within 20 characters
      
  8. Multiline string formatting in Python:

    • Description: Multiline strings can be formatted with placeholders or the .format() method.
    • Example Code:
      name = "Eva"
      age = 35
      multiline_formatted_string = (
          "Name: {}\n"
          "Age: {}"
      ).format(name, age)