\(\renewcommand\AA{\unicode{x212B}}\)
str()
, e.g.x = 'The meaning of life is ... '
answer = 42
y = x + str(answer) # This converts the number 42 to a string and joins
# it with the first string and then assigns y to a
# new string containing the concatenated string
print
command that
expects a string, e.g.print('The meaning of life is ... ')
print
command outputs a new line to the screen. To
suppress this behaviour add a comma after the string:# this now means the next print statement will continue from where this
# left the cursor
# In python 2 (in this case you cannot include the brackets)
print 'The meaning of life is ... ',
# the equivalent in python 3 is
#print('The meaning of life is ... ', end=' ')
x = 5
y = 6
# Python 2
print "X,Y:",str(x),str(y) # prints 'X,Y: 5 6' with a newline
#print("X,Y:",str(x),str(y)) # prints '('X,Y:', '5', '6')' with a newline
# Python 3
#print ("X,Y:",str(x),str(y)) # prints 'X,Y: 5 6' with a newline
str()
function:x = 'The meaning of life is ... '
answer = 42
print(x + str(answer))
Gives the output:
The meaning of life is ... 42
answer = 42
print('The meaning of life is ... {}'.format(answer))
Gives the output:
The meaning of life is ... 42
x = 1/2
print(x) # Prints 0!!! in Python 2 and 0.5 in Python 3
x
. The result is another
integer which in this case is the integer part of the real number
0.5. If, as in this case, the real number is required then we must
ask Python to use floating point numbers instead of integers. This
can be achieved in two ways:x = 1.0/2.0
print(x)
# or using the float function float()
x = 1
y = 2
print(float(x)/float(y))
Gives the output:
0.5
0.5
Type | Function | Example |
integer | int() | int(3.14159) => 3 |
float | float() | float(5) => 5.0 |
bool | bool() | bool(5) => True |
string | str() | str(5) => ‘5’ |