Tuesday, June 12, 2018

Type Conversion in Python

Converting the datatypes of value to another datatype .

Python has two types of type conversion

1. Implicit Type Conversion

Here, python automatically converts datatype or set datatype .


myInteger = 789

myFloat = 1.34

myResult = myInteger + myFloat

print(“Datatype is: ”, type(myInteger)) #Output: <class ‘int’>

print(“Datatype is: ”,type(myFloat)) #Output: <class ‘float’>

print(“Datatype is: ”, type(myResult)) #Output: <class ‘float’>

Here myResult automatically Convert datatype:

2. Explicit Type Conversion

Here, we can convert the values datatypes manullay.


myInteger = 789

myString = “248”

print(“Datatype is: ”, type(myInteger)) #Output: <class ‘int’>
print(“Datatype is: ”,type(myString)) #Output: <class ‘str’>

newInteger = int(mystring)

print(myInteger + myString) # Output ERRROR!!!!!!!!!!!!!!
print(myInteger + newInteger) # Output: 1037

Several Built-in Functions

Function Description
int(x, [,base]) Converts x to an integer. The base specifies the base if x is a string.
float(x) Converts x to a floating-point number.
Complex(real [,imag]) Create 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) Convert s to list.
set(s) Converts s to a set.
dict(d) Creates a dictionary. D must be a sequence of (key, value) tuples.
frozenset(s) Convert s to a frozen set
chr(x) Converts an integer to a character.
Unichr(x) Convert an integer to a Unicode Character
ord(x) Converts a single character to its integer value.
hex(x) Coverts an integer to a hexadecemal string.
oct(x) Coverts an integer to an octal string.

Prev: Dictionaries In Python

Next: Input, Output Functions in Python

No comments:

Post a Comment

Google+ Followers