Python Logo

String Formatting


Python string formatting is a powerful way to format strings in Python. It allows you to insert values into strings and format the strings in a variety of ways.

Basic string formatting

To format a string in Python, you use the % operator. The % operator is followed by a format specifier, which tells Python how to format the value.

Example:

 

Python

name = "Alice"
age = 25

# Format the string using the %s format specifier
formatted_string = "Hello, %s! You are %s years old." % (name, age)

print(formatted_string)
 

Output:

 

Hello, Alice! You are 25 years old.
 

Named string formatting

Python also supports named string formatting. Named string formatting allows you to insert values into strings using named placeholders.

Example:

 

Python

name = "Alice"
age = 25

# Format the string using named placeholders
formatted_string = f"Hello, {name}! You are {age} years old."

print(formatted_string)
 

Output:

 

Hello, Alice! You are 25 years old.
 

Formatting strings with different data types

Python supports a variety of format specifiers for formatting different data types. For example, the %d format specifier is used to format integers, the %f format specifier is used to format floating-point numbers, and the %s format specifier is used to format strings.

Here is a table of some common format specifiers:




 

Format specifier

Data type

Example

%d

Integer

10

%f

Floating-point number

3.14

%s

String

"Hello, world!"

Formatting strings with alignment and precision

Python also allows you to specify the alignment and precision of formatted strings. For example, the : character can be used to specify the minimum field width of a formatted value. The . character can be used to specify the precision of a formatted floating-point number.

Example:

 

Python

# Format the string with a minimum field width of 10 and a precision of 2 decimal places
formatted_string = f"The value of pi is: {3.14159:10.2f}"

print(formatted_string)
 

Output:

 

The value of pi is:     3.14
 

Conclusion

Python string formatting is a powerful tool for formatting strings in Python. By understanding how to use string formatting, you can write more readable and maintainable code.