C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Padding: A ":" character is applied as padding. The "greater than" character, followed by 10s, means right-align in a string of length 10.
Python program that uses format
# Format this number with a comma.
result = format(1000, ",")
print(result)
# Align to the right of 10 chars, filling with ":" and as a string.
result = format("cat", ":>10s")
print(result)
Output
1,000
:::::::cat
Number: The "{number}" pattern in the string has the "cat_number" inserted into it. The same thing happens with "color."
Tip: We assign names to variables in the argument list of format(). The variables are bound to names in this way.
Python program that uses format
cat_color = "orange"
cat_number = 10
# Use format method on string.
# ... Assign variables to names in pattern.
result = "cat {number} is {color}".format(number=cat_number, color=cat_color)
print(result)
Output
cat 10 is orange
Here: The dog_size and dog_color variables are placed inside the format string.
Python program that uses format literal
dog_color = "orange"
dog_size = 100
# Use format literal.
result = f"the dog weighs {dog_size} and is {dog_color}"
print(result)
Output
the dog weighs 100 and is orange