In Python, you can print integers using the %d
placeholder.
value = 10
print("Count: %d" % value)
Output
Count: 10
This code snippet uses the %d
format specifier to print an integer value.
Floating-point numbers can be printed using %f
. You can also control the number of decimal places with %.nf
.
price = 12.34
pi_value = 3.14159
print("Price: %f" % price)
print("Pi: %.2f" % pi_value)
Output
Price: 12.340000
Pi: 3.14
Here, %f
prints the floating-point number, and %.2f
prints the number rounded to 2 decimal places.
Use %s
for strings and %c
for characters.
name = "John"
character = 'A'
print("Name: %s" % name)
print("First letter: %c" % character)
Output
Name: John
First letter: A
For hexadecimal and octal representations, %x
, %X
, and %o
are used.
hex_value = 255
oct_value = 64
print("Hex: %x" % hex_value) # Lowercase
print("Hex: %X" % hex_value) # Uppercase
print("Octal: %o" % oct_value)
Output
Hex: ff
Hex: FF
Octal: 100
To print the percentage sign itself, use %%
.
percentage = 75.5
print("Percentage: %.2f%%" % percentage)
Output
Percentage: 75.50%
You can also use the .format
method and f-strings for more flexible printing.
value = 10
print("Count: {}".format(value))
print(f"Count: {value}")
Output
Count: 10
Count: 10
In conclusion, the Python print
function offers a wide range of formatting options, allowing for precise control over the output of integers, floating-point numbers, strings, and other data types. By mastering these techniques, you can enhance the readability and presentation of your output.
file
argument in the print function.end
argument, e.g., print("text", end='')
..format
, you can mix various types in one print statement.%f
prints the full floating-point number, while %.nf
allows control over the number of decimal places.\n
for a newline, \t
for a tab, etc.CloneCoding
Innovation Starts with a Single Line of Code!