String formating
String Formatting
2.5 String Formatting
String formatting is a powerful feature in Python that allows us to create dynamic strings by substituting variables or values into predefined placeholders. Python supports multiple approaches to string formatting, including the older % operator and the newer str.format() method. Here’s an example using str.format():
Python uses C-style string formatting to create new, formatted strings. The "%" operator is used to format a set of variables enclosed in a "tuple" (a fixed size list), together with a format string, which contains normal text together with "argument specifiers", special symbols like "%s" and "%d".
Let's say you have a variable called "name" with your user name in it, and you would then like to print(out a greeting to that user.)
# This prints out "Hello, John!"
name = "John"
print("Hello, %s!" % name)
Hello, John!
To use two or more argument specifiers, use a tuple (parentheses):
# This prints out "John is 23 years old." name = "John" age = 23 print("%s is %d years old." % (name, age))
Here are some basic argument specifiers you should know:
%s - String (or any object with a string representation, like numbers)
%d - Integers
%f - Floating point numbers
%.f - Floating point numbers with a fixed amount of digits to the right of the dot.
%x/%X - Integers in hex representation (lowercase/uppercase)