Typecasting in python

Casting is when you convert a variable value from one type to another. This is, in Python, done with functions such as int() or float() or str(). The various casting methods that are in python are :

Function Description
int(x [,base]) Converts x to an integer. base specifies the base if x is a string.
long(x [,base] ) Converts x to a long integer. base specifies the base if x is a string.
float(x) Converts x to a floating-point number.
complex(real [,imag]) Creates a complex number.
str(x) Converts object x to a string representation.
repr(x) Converts object x to an expression string.
eval(str) Evaluates a string and returns an object.
tuple(s) Converts s to a tuple.
list(s) Converts s to a list.
set(s) Converts s to a set.
dict(d) Creates a dictionary. d must be a sequence of (key,value) tuples.
frozenset(s) Converts s to a frozen set.
chr(x) Converts an integer to a character.
unichr(x) Converts an integer to a Unicode character.
ord(x) Converts a single character to its integer value.
hex(x) Converts an integer to a hexadecimal string.
oct(x) Converts an integer to an octal string.

Example

# USUAL STRING
var1 = "2"
print('%s' % var1)  # print as string

# STRING TO INTEGER
var2 = int(var1) + 20
print('%d' % var2)  # print as integer

#INTEGER TO FLOAT
var3 = 300
print('%F' % var3)

# FLOAT TO INTEGER
var4 = int(100.36)
print('%d' % var4)

# STRING TO INTEGER
var6 = str(1) + " is you ranked, " + "and you are best "
print('%s' % var6)

Output

2
22
300.000000
100
1 is you ranked, and you are best