How To Use String Formatters in Python 3

How To Use String Formatters in Python 3

How To Use String Formatters in Python 3

String formatters are a useful feature in Python 3 that allows you to create formatted strings. With string formatters, you can easily insert variables, values, and expressions into your strings.

Types of String Formatters

Python 3 has several types of string formatters:

  • % operator
  • str.format() method
  • f-strings

% Operator

The % operator is the oldest and most basic string formatter in Python. It allows you to format strings using placeholders for variables, values, and expressions.

      
# Example 1
name = "John"
age = 25
print("My name is %s and I am %d years old." % (name, age))

# Example 2
price = 12.50
print("The price is %.2f dollars." % price)
      
    

In Example 1, we use the %s and %d placeholders to insert the name and age variables into the string. In Example 2, we use the %.2f placeholder to format the price variable to two decimal places.

str.format() Method

The str.format() method is a more modern and flexible way to format strings in Python. It uses placeholders inside curly braces {} to insert variables, values, and expressions into the string.

      
# Example 1
name = "John"
age = 25
print("My name is {} and I am {} years old.".format(name, age))

# Example 2
price = 12.50
print("The price is {:.2f} dollars.".format(price))
      
    

In Example 1, we use the curly braces {} as placeholders for the name and age variables. In Example 2, we use the {:.2f} placeholder to format the price variable to two decimal places.

f-strings

f-strings are the newest and most concise way to format strings in Python. They use curly braces {} as placeholders and allow you to insert variables, values, and expressions directly into the string.

      
# Example 1
name = "John"
age = 25
print(f"My name is {name} and I am {age} years old.")

# Example 2
price = 12.50
print(f"The price is {price

Комментарии

Популярные сообщения из этого блога

How To Modify CSS Classes in JavaScript

How To Backup MySQL Databases on an Ubuntu VPS

How To Backup PostgreSQL Databases on an Ubuntu VPS