Commonly used python data type conversion function summary

  • 2020-04-02 13:28:02
  • OfStack

1, CRH (I)
The CHR () function returns the string corresponding to the ASCII code.

>>> print chr(65)
A
>>> print chr(66)

>>> print chr(65)+chr(66)
AB

2, the complex (real [, imaginary])
The complex() function converts a string or number to a complex number.

>>> complex("2+1j")
(2+1j)
>>> complex("2")
(2+0j)
>>> complex(2,1)
(2+1j)
>>> complex(2L,1)
(2+1j)

3, float (x)
The float() function converts a number or string to a float.
>>> float("12")
12.0
>>> float(12L)
12.0
>>> float(12.2)
12.199999999999999

4, hex (x)
The hex() function converts integers to hexadecimal Numbers.
>>> hex(16)
'0x10'
>>> hex(123)
'0x7b'

5, long (x [, base])
The long() function converts Numbers and strings into integers, with base as the optional base.
>>> long("123")
123L
>>> long(11)
11L

6, the list (x)
The list() function converts a sequence object into a list. Such as:
>>> list("hello world")
['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
>>> list((1,2,3,4))
[1, 2, 3, 4]

7, int (x [, base])
The int() function converts a number and a string to an integer, with base as the optional cardinality.
>>> int(3.3)
3
>>> int(3L)
3
>>> int("13")
13
>>> int("14",15)
19

[8, min (x, y, z... )
The min() function returns the minimum value of a given parameter, which can be a sequence.
>>> min(1,2,3,4)
1
>>> min((1,2,3),(2,3,4))
(1, 2, 3)

[9, Max (x, y, z... )
The Max () function returns the maximum value of a given parameter, which can be a sequence.
>>> max(1,2,3,4)
4
>>> max((1,2,3),(2,3,4))
(2, 3, 4)

, oct 10 (x)
The oct() function converts given integers into octal Numbers.
>>> oct(8)
'010'
>>> oct(123)
'0173'

11, word (x)
The ord() function returns the ASCII or Unicode value of a string parameter.
>>> ord("a")
97
>>> ord(u"a")
97

12, STR (obj)
The STR () function converts the object to a printable string.
>>> str("4")
'4'
>>> str(4)
'4'
>>> str(3+2j)
'(3+2j)'

13, the tuple (x)
The tuple() function converts a sequence object to a tuple.
>>> tuple("hello world")
('h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd')
>>> tuple([1,2,3,4])
(1, 2, 3, 4)

14, type (x)
Type () can take anything as a parameter and return its data type. Integers, strings, lists, dictionaries, tuples, functions, classes, modules, and even type objects can all be accepted as arguments by the type function.
>>> type(1)           
<type 'int'>
>>> li = []
>>> type(li)          
<type 'list'>
>>> import odbchelper
>>> type(odbchelper)  
<type 'module'>
>>> import types      
>>> type(odbchelper) == types.ModuleType
True


Related articles: