Sobes.tech
Junior

What types of string formatting exist in Python?

sobes.tech AI

Answer from AI

  • Old formatting (%)

    Uses the % operator to insert values into a string template.

    name = "Alice"
    age = 30
    print("My name is %s and I am %d years old." % (name, age))
    
  • .format() method

    A newer and more flexible way of formatting. Uses curly braces {} as placeholders.

    city = "New York"
    temperature = 25.5
    print("The temperature in {} is {} degrees Celsius.".format(city, temperature))
    
  • f-strings (Formatted String Literals)

    Introduced in Python 3.6. The most modern and recommended method. Allows embedding expressions directly in the string using the f prefix.

    product = "Laptop"
    price = 1200
    print(f"The {product} costs ${price}.")
    
  • Template strings

    Found in the string module. Less powerful but safer for working with untrusted data, as they do not execute arbitrary code in placeholders.

    from string import Template
    
    data = {'user': 'Bob'}
    t = Template('Hello, $user!')
    print(t.substitute(data))