Python语言中的显式类型转换

我们所有人都可以声明并使用数据类型。我们是否曾经想过他们的相互转换?在本文中,我们将学习如何使用Python(也称为类型转换)中的内置函数来转换这些数据类型。类型转换有两种类型:隐式和显式。在本模块中,我们将仅讨论显式类型转换。

现在让我们看一些基本的和类型的转换

Python中的整数类型转换

int()函数允许我们将任何数据类型转换为整数。它正好接受两个参数,即Base和Number,其中Base表示整数值所属的基数(binary [2],octal [8],十六进制[16])。

Python中的浮点类型转换

float()函数允许我们将任何数据类型转换为浮点数。它只接受一个参数,即需要转换的数据类型的值。

示例

#Type casting
   value = "0010110"
   # int base 2
p = int(value,2)
print ("integer of base 2 format : ",p)
# default base
d=int(value)
print ("integer of default base format : ",d)
   # float
e = float(value)
print ("corresponding float : ",e)

输出结果

integer of base 2 format : 22
integer of default base format : 10110
corresponding float : 10110.0

在上面的代码中,我们还在Python中使用base转换了整数

Python中的元组类型转换

tuple()函数允许我们转换为元组。它只接受一个参数(字符串或列表)。

Python中的列表类型转换

list()函数使我们可以将任何数据类型转换为列表类型。它只接受一个参数。

Python中的字典类型转换

dict()函数用于将顺序(键,值)的元组转换为字典。键本质上必须是唯一的,否则重复的值将被覆盖。

示例

#Type casting
   str_inp = 'Nhooo'
# converion to list
j = list(str_inp)
print ("string to list : ")
print (j)
# conversion to tuple
i = tuple(str_inp)
print ("string to tuple : ")
print (i)
# nested tuple
tup_inp = (('Tutorials', 0) ,('Point', 1))
# conversion to dictionary
c = dict(tup_inp)
print ("list to dictionary : ",c)
# nested list
list_inp = [['Tutorials', 0] ,['Point', 1]]
# conversion to dictionary
d = dict(list_inp)
print ("list to dictionary : ",d)

输出结果

string to list :
['T', 'u', 't', 'o', 'r', 'i', 'a', 'l', 's', 'p', 'o', 'i', 'n', 't']
string to tuple :
('T', 'u', 't', 'o', 'r', 'i', 'a', 'l', 's', 'p', 'o', 'i', 'n', 't')
list to dictionary : {'Tutorials': 0, 'Point': 1}
list to dictionary : {'Tutorials': 0, 'Point': 1}

Python中的字符串类型转换

str()函数用于将整数或浮点数转换为字符串。它只接受一个参数。

Python中的Ascii chr()和ord()类型转换

chr()-此函数用于将整数类型转换为字符类型。

ord()-此函数用于将字符类型转换为整数类型。

示例

#Type casting
   char_inp = 'T'
#converting character to corresponding integer value
print ("corresponding ASCII VALUE: ",ord(char_inp))
   int_inp=92
#converting integer to corresponding Ascii Equivalent
print ("corresponding ASCII EQUIVALENT: ",chr(int_inp))
#integer and float value
inp_i=231
inp_f=78.9
# string equivalent
print ("String equivalent",str(inp_i))
print ("String equivalent",str(inp_f))

输出结果

corresponding ASCII VALUE: 84
corresponding ASCII EQUIVALENT: \
String equivalent 231
String equivalent 78.9

结论

在本文中,我们学习了Python 3.x中的显式类型转换。或更早。