How to Output Different Python Data Types


In this example we will show how to print String data, Hexadecimal/Decimal/Octal Integer, Float and Newline in Python.

2. Print String

Code:

strHello = 'Hello World'
print(strHello)
print('Hello World')

Output:

Hello World
Hello World

3. Print Hexadecimal, Decimal, Octal Integer

Code:

%x --- hex 
%d --- dec 
%o --- oct 
nHex = 0xFF
print("nHex = %x,nDec = %d,nOct = %o" %(nHex,nHex,nHex))

Output:

nHex = ff,nDec = 255,nOct = 377

4. Print Floating Point Number (float)

Code:

pi = 3.141592653
print('%10.3f' % pi)
# Field width 10, precision 3

print("pi = %.*f" % (3,pi))
#Use * to read field width or precision from the following tuple
pi = 3.142

print('%010.3f' % pi)
#Fill the blank with 0

print('%-10.3f' % pi)
#Align left

print('%+f' % pi)
#Show sign

Output:

    3.142
pi = 3.142
000003.142
3.142
+3.142000

5. Newline in Print

When using the print function, the output has a newline at the end by default:

for x in range(0,10):
    print(x)

Output:

0
1
2
3
4
5
6
7
8
9

If we do not want a newline, just use this method:

Code:

for x in range(0,10):
    print(x, end=" ")

Output:

0 1 2 3 4 5 6 7 8 9

Here we specify “end” value of output. In this example, newline will not be used as the end of the output.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments