# Define variables name = "Alice" age = 25 # Use the % operator for string formatting formatted_string = "Hello, %s. You are %d years old." % (name, age) print(formatted_string)
Hello, Alice. You are 25 years old.
# Define variables name = "Bob" age = 30 # Use the str.format() method for string formatting formatted_string = "Hello, {}. You are {} years old.".format(name, age) print(formatted_string)
Hello, Bob. You are 30 years old.
# Define variables name = "Charlie" age = 35 # Use named placeholders with the str.format() method formatted_string = "Hello, {name}. You are {age} years old.".format(name=name, age=age) print(formatted_string)
Hello, Charlie. You are 35 years old.
# Define variables name = "Diana" age = 40 # Use f-strings for string formatting formatted_string = f"Hello, {name}. You are {age} years old." print(formatted_string)
Hello, Diana. You are 40 years old.
# Define variables a = 5 b = 10 # Use expressions within f-strings formatted_string = f"The sum of {a} and {b} is {a + b}." print(formatted_string)
The sum of 5 and 10 is 15.
# Define a float variable pi = 3.14159 # Using the % operator formatted_string = "Pi approximately equals %.2f" % pi print(formatted_string) # Using the str.format() method formatted_string = "Pi approximately equals {:.2f}".format(pi) print(formatted_string) # Using f-strings formatted_string = f"Pi approximately equals {pi:.2f}" print(formatted_string)
Pi approximately equals 3.14 Pi approximately equals 3.14 Pi approximately equals 3.14
# Define a list of names names = ["Alice", "Bob", "Charlie"] # Using the % operator for name in names: print("%-10s" % name) # Left-aligned with padding # Using the str.format() method for name in names: print("{:<10}".format(name)) # Left-aligned with padding # Using f-strings for name in names: print(f"{name:<10}") # Left-aligned with padding
Alice Bob Charlie Alice Bob Charlie Alice Bob Charlie
# Define variables name = "Emily" balance = 1234.567 # Using the % operator formatted_string = "Name: %-10s | Balance: $%8.2f" % (name, balance) print(formatted_string) # Using the str.format() method formatted_string = "Name: {:<10} | Balance: ${:8.2f}".format(name, balance) print(formatted_string) # Using f-strings formatted_string = f"Name: {name:<10} | Balance: ${balance:8.2f}" print(formatted_string)
Name: Emily | Balance: $ 1234.57 Name: Emily | Balance: $ 1234.57 Name: Emily | Balance: $ 1234.57