Casting in Python

Casting in Python has quite a few practical applications. Here's what you need to know about casting in Python.

Casting in Python has quite a few practical applications. Here's what you need to know about casting in Python .

Casting in Python Picture 1Casting in Python Picture 1

Define variable type

Sometimes you may want to specify a type for a variable. This can be done by casting or casting in Python.

Python is an object-oriented language, so it uses classes to define data types, including its 'primitive' types.

Casting in Python is done using constructors:

  1. Int()- Constructs an integer from an integer, a float character (by removing all decimals) or a string literal (providing the string representation of an integer).
  2. Float()- Construct a float from an integer, a float, or a string literal (provide the string representation of a float or an integer)
  3. Str()- Build a string from a range of data types, including string, integer string, and float character string.

For example:

Integer:

x = int(1) # x sẽ là 1 y = int(2.8) # y sẽ là 2 z = int("3") # z sẽ là 3

Float:

x = str("s1") # x sẽ là 's1' y = str(2) # y sẽ là '2' z = str(3.0) # z sẽ là '3.0'

Table of data type casting functions in Python

STT Function and description
first int(x [,base]) casts to int
2 long(x [,base] ) casts to long int.
3 float(x) casts float.
4 complex(real [,imag]) casts complex number.
5 str(x) casts string.
6 repr(x) casts to the expression string.
7 eval(str) casts string to object.
8 tuple(s) casts tuple type.
9 list(s) casts the type list.
ten set(s) casts the set type.
11 dict(d) casts dictionary.
twelfth frozenset(s) casts the frozen set type.
13 chr(x) casts print to char
14 unichr(x) casts an int to a Unicode character.
15 ord(x) casts the character to int.
16 hex(x) converts integer to hexadecimal string.
17 oct(x) casts an integer to an octal string.

Above is the basic information you need to know about casting in Python . Hope the article is useful to you.

4 ★ | 1 Vote