Home >>Python Tutorial >Python Casting With Example

Python Casting With Example

Specifying Any Kind Of Variable Type | Python Casting

When you as a developer will get quite used to the whole Python programming language platform then you might often come across certain times when you will be required to specify any particular variable into a specific type.

This part will prepare you for those instances and what you can do to accomplish that particular task of assigning a particular type to a variable is known as casting.

You will also be learning about Python casting to String.

As we have mentioned previously in this tutorial that Python as a programming language is often categorized as an object-oriented programming language.

This means that Python as a programming language uses various classes to define a lot of its data types.

All kinds of primitive data types are also defined with the help of classes in this programming language.

This further implies that all kinds of casting that are done in Python are done by using various different types of construction functions. And some of those construction functions are mentioned below.

  • int ( )

This Python cast function is used to construct any integral number with the help of an integral literal, a string literal (obtained by rounding down the previous whole number), or a float literal (a whole number is represented by providing a string).

  • float ( )

This construction function helps in the construction of any float number with the help of a float literal, an integral literal, or a string literal (if a float or an integer is represented by a string).

  • str ( )

This construction function helps in the construction of any string with the help of a lot of different data types.

And these different data types might include integral literals, float literals, and strings.

Now to understand all these concepts in a better way, we’ll be looking at some kinds of examples for the points made under each of the Python casting objects types that are mentioned above.

So, the example of the construction type of integers is mentioned below.

x = int (1)       # x will be 1
y = int (2.6)    # y will be 2
z = int (“3”)    # z will be 3

The example of the construction type of floats is mentioned below.

x = float (1)            # x will be 1.0
y = float (2.6)         # y will be 2.6
z = float (“3”)         # z will be 3.0
w = float (“4.3”)     # w will be 4.3

The example of the construction type of strings is mentioned below.

X = str (“s1”)     # x will be ‘s1’
Y = str (2)          # y will be ‘2’
Z = str (3.0)       # z will be ‘3.0’

With this, we finish our casting part of the overall Python tutorial. And by the end of this part of the tutorial, you must be able to identify the Python casting objects.

No Sidebar ads