Python data type conversion functions include: 1. int() function; 2. float() function; 3. str() function; 4. list() function; 5. tuple() function; 6. dict() function; 7. set() function; 8. bytes() function; 9. complex() function. Detailed introduction: 1. int() function, this function is used to convert a number or a string with a numeric value into an integer; 2. float() function, this function is used to convert a number or string, etc.
The operating system for this tutorial: Windows 10 system, Python version 3.11.4, DELL G3 computer.
In Python, you can use a variety of functions to convert data types. The following are some commonly used data type conversion functions:
1, int(): This function is used to convert a number or a string with a numeric value into an integer. For example:
x = int(2.8) # x will be 2 y = int("3") # y will be 3
2, float(): This function is used to convert a number or string into a floating point number. For example:
x = float(2) # x will be 2.0 y = float("3.5") # y will be 3.5
3, str(): This function is used to convert other data types to strings. For example:
x = str(2) # x will be "2" y = str(3.5) # y will be "3.5"
4, list(): This function is used to convert an iterable object (such as a tuple or string) into a list. For example:
x = list((1, 2, 3)) # x will be [1, 2, 3] y = list("hello") # y will be ['h', 'e', 'l', 'l', 'o']
5, tuple(): This function is used to convert an iterable object into a tuple. For example:
x = tuple([1, 2, 3]) # x will be (1, 2, 3)
6, dict(): This function is used to create a dictionary. It can construct a dictionary from a nested sequence of key-value pairs. For example:
x = dict([(1, 'one'), (2, 'two')]) # x will be {1: 'one', 2: 'two'}
7, set(): This function is used to convert an iterable object into a set. For example:
x = set([1, 2, 3, 3]) # x will be {1, 2, 3}
8, bytes(): This function is used to convert an object into a bytes object. For example:
x = bytes([1, 2, 3]) # x will be b'\x01\x02\x03'
9, complex(): This function is used to create a complex number. For example:
x = complex(1, 2) # x will be (1+2j)
The above are some basic functions for data type conversion in Python. It should be noted that some data types (such as dictionaries and custom objects) may not have built-in conversion methods. In this case, you may need to define the conversion method yourself or use a third-party library (such as pandas) to perform conversion.
The above is the detailed content of What are the Python data type conversion functions?. For more information, please follow other related articles on the PHP Chinese website!