脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Python学习之不同数据类型间的转换总结

Python学习之不同数据类型间的转换总结

2022-10-23 15:57渴望力量的哈士奇 Python

类型转换,就是将自身的数据类型变成新的数据类型,并拥有新的数据类型的所有功能的过程。本文将详细为大家介绍如何在Python中实现不同数据类型的转换,感兴趣的可以了解一下

字符串与数字类型的转换

什么是类型转换?—> 将自身的数据类型变成新的数据类型,并拥有新的数据类型的所有功能的过程即为类型转换

为什么做类型转换?—> 为了方便更好的帮助处理业务,将类型变更为更适合业务场景的类型

举例:比如 a = '1' ,这是一个字符串类型,所以它无法执行数字类型的操作。

字符串与数字之间转换的要求

str —> number :必须是由数字组成的字符串才可以通过类型转换转为数字类型

int_str = '1024' ; float_str = '3.1415926'

number —> str : 无任何要求

字符串与数字之间的转换函数

原始类型 目标类型 函数 举例
整型 字符串 str new_str = str(123456)
浮点型 字符串 str new_str = str(3.1515926)
字符串 整型 int new_int = int(‘1234’)
字符串 浮点型 int new_float = int(‘3.1415926’)

示例如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
str_int = '1024'
new_int = int(int_str)
print(new_int)
 
# 执行结果如下:
# >>> 1024
# >>> <class 'int'>
 
 
int_str = 3.1415926
new_str = str(int_str)
print(new_str)
print(type(new_str))
 
# 执行结果如下:
# >>> 3.1415926
# >>> <class 'str'>
 
 
int_and_str = '123abc'          # 只有数字组成的字符串才可以通过类型转换转为数字类型
new_int = int(int_and_str)
print(new_int)
 
# 执行结果如下:
# >>> ValueError: invalid literal for int() with base 10: '123abc'

字符串与列表之间的转换

split() 函数 - 字符串转列表

split() 函数 的功能:将字符串以一定的规则切割,并转换成列表。

split() 函数 的用法:string.split(sep=Node, maxsplit=-1) ;

  • sep : 为作为切割识别的规则符号,不填写的情况下默认切割规则符号为空格;如果字符串不存在空格,则不分割成列表。
  • maxsplit:将字符串以切割规则符号切割的次数,默认为 -1 , 即不限制次数。
  • split() 函数 的 返回值为列表

示例如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
name = 'My name is Neo'
name_list = name.split()
 
print(name_list)
 
# 执行结果如下:
# >>> ['My', 'name', 'is', 'Neo']
# >>> 可以看到已经将 'name' 以空格为切割规则符号切割成了每个单词为一个元素的列表
 
 
test_int = '1,  2,    3,     4'
test_int_list = test_int.split(',')
 
print(test_int_list)
 
# 执行结果如下:
# >>> ['1', '  2', '    3', '     4']
# >>> 可以看到已经将 'test_int' 以逗号为切割规则符号切割成了每个单词为一个元素的列表
 
 
test_str = 'a|b|c|d|e'
test_str_list = test_str.split('|', 2)
 
print(test_str_list)
 
# 执行结果如下:
# >>> ['a', 'b', 'c|d|e']
# >>> 可以看到已经将 'test_str_list' 以 '|' 为切割规则符号切割成了两次
 
 
error_str = ' a~b~c '
test_error_str = error_str.split('')
print(test_error_str)
 
# 执行结果如下:
# >>> ValueError: empty separator          注意:split()函数是不可以用空字符串作为切割规则符号的

join() 函数 - 列表转字符串

split() 函数 的功能:将列表以一定的规则切割,并转换成字符串。

split() 函数 的用法:'sep'.join(iterable) ;

  • sep:生成字符串用来分割列表每个元素的符号
  • iterable:非数字类型的列表或元组或集合
  • join() 函数 的 返回值为一个字符串
  • 需要注意的是:只有列表的元素为字符串的情况下才可以将列表转为字符串,列表元素为 数字、元组、字典等数据类型的情况下,则会报错。

示例如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
test_info = ['a', 'b', 'c']
new_info = '-'.join(test_info)
 
print(new_info)
 
# 执行结果如下:
# >>> a-b-c
 
 
test_info_int = [1, 2, 3, 4]
new_info_int = '-'.join(test_info_int)
 
print(new_info_int)
 
# 执行结果如下:
# >>> TypeError: sequence item 0: expected str instance, int found
 
 
test_info_tuple = [(1, ), (2, 3, 4)]
new_info_tuple= '-'.join(test_info_tuple)
 
print(new_info_tuple)
 
# 执行结果如下:
# >>> TypeError: sequence item 0: expected str instance, int found

数据类型转换 - 小练习

将字符串 'a e f h j k d l' , 转换为列表并进行排序,然后再转为字符串。

代码示例如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
sort_str = 'a e f h j k d l'
sort_str_list = sort_str.split(' ')
print(sort_str_list)
 
# 执行结果如下:
# >>> ['a', 'e', 'f', 'h', 'j', 'k', 'd', 'l']
 
sort_str_list.sort()
print(sort_str_list)
 
# 执行结果如下:
# >>> ['a', 'd', 'e', 'f', 'h', 'j', 'k', 'l']
 
sort_str = '|'.join(sort_str_list)
print(sort_str)
print(type(sort_str))
 
# 执行结果如下:
# >>> a|d|e|f|h|j|k|l
# >>> <class 'str'>

拓展 - sorted() 函数

sorted() 函数区别于 sort() 函数。sort() 函数为列表的内置函数,而sorted() 函数为python的内置函数,可以处理所有的数据类型。

示例如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
sort_str_new = 'aefhjkdc'
result = sorted(sort_str_new)
 
print(result)
 
# 执行结果如下:
# >>> ['a', 'c', 'd', 'e', 'f', 'h', 'j', 'k']
 
 
print(''.join(result))
 
# 执行结果如下:
# >>> acdefhjk

字符串与bytes通过编解码进行转换

什么是 bytes ?(比特类型) —> bytes 是一种二进制数据流,也是一种可传输的类型,在各个编程语言中都存在。也可以认为它是一种特殊的字符串,因为它长得和字符串几乎一模一样,同时也拥有字符串几乎所有的内置函数。我们完全可以像操作字符串一样操作 比特类型 (bytes),只不过字符串前需要加上 b 的标识。

示例如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
bt = b'my name is Neo'
print('\'bt\'的值为:', bt, ';\'bt\'的类型为:', type(bt))
 
# 执行结果如下:
# >>> 'bt'的值为: b'my name is Neo' ;'bt'的类型为: <class 'bytes'>
 
 
print(bt.capitalize())
 
# 执行结果如下:
# >>> b'My name is neo'
 
 
print(bt.replace('Neo', 'Jack'))
 
# 执行结果如下:
# >>> TypeError: a bytes-like object is required, not 'str'    这里的报错是因为我们替换的类型为字符串类型,正确的写法如下
 
 
print(bt.replace(b'Neo', b'Jack'))
 
# 执行结果如下:
# >>> b'my name is Jack'
 
 
print(bt[0])
print(bt[-1])
print(bt[3:8])
 
# 执行结果如下:
# >>> 109      这里的109是 'n' 的二进制流的显示方式
# >>> 111      这里的111是 'o' 的二进制流的显示方式
# >>> b'name '
 
 
print('\'N\'字符的索引位置为:', bt.find(b'N'))
 
# 执行结果如下:
# >>> 'N'字符的索引位置为: 11
 
 
test_info = b'my name is \'李雷\''
print(test_info)
 
# 执行结果如下:
# >>> SyntaxError: bytes can only contain ASCII literal characters.    # 报错信息为"bytes"类型只支持ASCII码的字符
# 由此也引出了下文的 encode() 函数 与 decode() 函数

encode() 函数 - 字符串转 bytes

encode() 函数 的功能:将字符串转为比特(byte)类型

encode() 函数 用法:

用法:string.encode(encoding='utf-8', errors='strict')

参数:encoding 与 errors

  • encoding 转换成的编码格式,如ascii、gbk、默认为 ‘utf-8’
  • errors 出错时的处理方法,默认为 strict ;直接报错误,也可以选择 ignore 忽律错误
  • 返回值为一个比特(bytes)类型

示例如下:

?
1
2
3
4
5
6
7
8
test_str = 'my name is HanMeimei'
bytes_str = test_str.encode('utf-8')
print(bytes_str)
print(type(bytes_str))
 
# 执行结果如下:
# >>> b'my name is HanMeimei'
# >>> <class 'bytes'>

decode() 函数 - bytes 转字符串

decode() 函数 的功能:将比特(byte)类型转为字符串

decode() 函数 用法:

用法:string.encode(encoding='utf-8', errors='strict') ;

参数:encoding 与 errors; 注意,这里的 encoding 是解码的作用,encode() 函数 的 encoding 是 编码的作用。

  • encoding 转换成的编码格式,如ascii、gbk、默认为 ‘utf-8’
  • errors 出错时的处理方法,默认为 strict ;直接报错误,也可以选择 ignore 忽律错误
  • 返回值为一个字符串类型

示例如下:

?
1
2
3
4
5
6
7
8
bytes_str = b'Python is very good'
test_str = bytes_str.decode('utf-8')
print(test_str)
print(type(test_str))
 
# 执行结果如下:
# >>> Python is very good
# >>> <class 'str'>
?
1
2
3
4
5
6
7
8
9
10
11
str_date = 'my name is \'亚当\''
byte_date = str_date.encode('utf-8')
print(byte_date)
 
# 执行结果如下:
# >>> b"my name is '\xe4\xba\x9a\xe5\xbd\x93'"  这是 utf-8 转化的中文的样子
 
print(byte_date.decode('utf-8'))
 
# 执行结果如下:
# >>> my name is '亚当'

列表、集合、元组的转换

列表元组集合间转换的函数

原始类型 目标类型 函数 举例
列表 集合 set new_set = set([1, 2, 3, 4, 5])
列表 元组 tuple new_tuple = ([1, 2, 3, 4, 5]
元组 集合 set new_set = set((1, 2, 3, 4, 5))
元组 列表 list new_set = set((1, 2, 3, 4, 5))
集合 列表 list new_list = list({1, 2, 3, 4, 5})
集合 元组 tuple new_tuple = tuple({1, 2, 3, 4, 5})

到此这篇关于Python学习之不同数据类型间的转换总结的文章就介绍到这了,更多相关Python数据类型转换内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/weixin_42250835/article/details/123264066

延伸 · 阅读

精彩推荐
  • Pythonpython实现文本文件合并

    python实现文本文件合并

    本文给大家汇总介绍了3种合并文本文件的方法,程序的实现思路都非常不错,这里推荐给大家,有需要的小伙伴可以参考下。...

    Python教程网5402020-08-05
  • Pythonpython简单文本处理的方法

    python简单文本处理的方法

    这篇文章主要介绍了python简单文本处理的方法,涉及Python针对文本文件及字符串操作的相关技巧,需要的朋友可以参考下...

    speedmancs7862020-07-21
  • Python解决hive中导入text文件遇到的坑

    解决hive中导入text文件遇到的坑

    这篇文章主要介绍了解决hive中导入text文件遇到的坑,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...

    水墨石11652021-10-06
  • Python使用 tqdm 在 Python 应用中显示进度

    使用 tqdm 在 Python 应用中显示进度

    如果你的程序需要一段时间才能显示结果,可通过显示它的进度来避免让用户感到沮丧。 ...

    Linux中国13412021-01-07
  • PythonPython的Socket编程过程中实现UDP端口复用的实例分享

    Python的Socket编程过程中实现UDP端口复用的实例分享

    这篇文章主要介绍了Python的Socket编程过程中实现UDP端口复用的实例分享,文中作者用到了Python的twisted异步框架,需要的朋友可以参考下 ...

    liweisnake5962020-08-17
  • Pythondjango js实现部分页面刷新的示例代码

    django js实现部分页面刷新的示例代码

    今天小编就为大家分享一篇django js实现部分页面刷新的示例代码,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...

    云中不知人8482021-02-26
  • PythonPython函数中的函数(闭包)用法实例

    Python函数中的函数(闭包)用法实例

    这篇文章主要介绍了Python函数中的函数(闭包)用法,结合实例形式分析了Python闭包的定义与使用技巧,需要的朋友可以参考下...

    小谈博客5302020-08-16
  • PythonPython 内置函数速查表一览

    Python 内置函数速查表一览

    这篇文章主要介绍了Python 内置函数速查表,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...

    Jairoguo11412021-11-21