![]() In Type Casting, loss of data may occur as we enforce the object to a specific data type.Explicit Type Conversion is also called Type Casting, the data types of objects are converted using predefined functions by the user.Python avoids the loss of data in Implicit Type Conversion.Implicit Type Conversion is automatically performed by the Python interpreter.Type Conversion is the conversion of an object from one data type to another data type.Here, we have used int() to perform explicit type conversion of num_string to integer type.Īfter converting num_string to an integer value, Python is able to add these two variables.įinally, we got the num_sum value i.e 35 and data type to be int. Notice the code, num_string = int(num_string) In the above example, we have created two variables: num_string and num_integer with str and int type values respectively. Output Data type of num_string before Type Casting: ĭata type of num_string after Type Casting: The example creates a string in the format: 'Mon Feb 22 10:15:00 2021'. Expression: field1 + datetime.timedelta (days100) Calculate a string representing the date using the ctime method in the datetime module. Print("Data type of num_sum:",type(num_sum)) Calculate a date by adding 100 days to the date value in a field. Print("Data type of num_string after Type Casting:",type(num_string)) Print("Data type of num_string before Type Casting:",type(num_string)) This type of conversion is also called typecasting because the user casts (changes) the data type of the objects.Įxample 2: Addition of string and integer Using Explicit Conversion num_string = '12' We use the built-in functions like int(), float(), str(), etc to perform explicit type conversion. Example Usage: Here age is a string object age '18' print(age) Converting a string to an integer intage int(age) print(intage) Output: Similar to the built-in str() method, Python also offers the handy int() method that takes a string object as an argument and returns an integer. In Explicit Type Conversion, users convert the data type of an object to required data type. Python has a solution for these types of situations which is known as Explicit Conversion. ![]() Python is not able to use Implicit Conversion in such conditions.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |