首页 > 编程语言 >python基础-数据类型间的转换

python基础-数据类型间的转换

时间:2022-10-21 18:24:26浏览次数:48  
标签:__ 转换 python 数据类型 字符串 test str print

数据类型转换:将自身数据类型转化成新的数据类型,并拥有新数据类型相关操作的过程;

为方便更好的帮助处理业务,将数据变更为更适合业务场景的类型;

a = '1',  此时想使用数字的数学操作,就需要先将字符串转化为数字类型;

 

1.数字与字符串间的转换

# 字符串转换成整数
a = '34'
b = int(a)
print(b)  # 34
# 此时字符串内必须是整数,否则会报错
# print(int('45.6'))  # ValueError: invalid literal for int() with base 10: '45.6'

# 字符串转换成浮点数
print(float('45.6'))  # 45.6
print(type(float('45.6')))  # <class 'float'>
print(float('45'))  # 45.0

# 数字转换成字符串
c = 34
print(str(c))  # 34
print(type(str(c)))  # <class 'str'>
print(str(45.6))  # 45.6

 

2.字符串与列表之间的转换

  字符串转换成列表:spring.split(sep=分割符, maxsplit=最大分割次数);

  列表转换成字符串:'分割符号'.join(可迭代对象);可迭代对象存储的数据不能是数字类型;

str_test = 'i am a teacher'
print(str_test.split())  # ['i', 'am', 'a', 'teacher'] (默认分割符是空格、默认分割次数为全部)
print(str_test.split(maxsplit=2))  # ['i', 'am', 'a teacher']
print('wer#ty#67'.split('#', 1))  # ['wer', 'ty#67']
# 若指定的分割符不存在,则完整字符串作为一个元素存入列表
print('i love you'.split('!'))  # ['i love you']
# 分割符不能是空字符串,会报错
# print(a.split(''))  # ValueError: empty separator
text = "23,王伟,2-1"
print(text.split(','))  # ['23', '王伟', '2-1'] (此时2-1属于字符串)

# print(' '.join(['python', 56]))  # TypeError: sequence item 1: expected str instance, int found
print(' '.join(['python', 'go']))  # python go
print('!!!'.join(('python', 'go')))  # python!!!go
print(' '.join({'python', 'go'}))  # go python
print(' '.join({'name': 'll', 'height': 178}))  # name height (字典拼接的是key)

 

3.字符串类型与比特类型的转换

  比特类型是一种特殊的二进制的数据流, bytes;

  可以看做是一种特殊的字符串,写法是字符串前加b;

  字符串转换bytes, string.encode(encoding=编码格式, errors='strict') 

    encoding是编码格式、默认是utf-8, 还可以是ascii或gbk等,errors是遇到错误时的操作,默认是strict直接抛异常、也可以指定为ignore, 忽略错误; 

  bytes转换成字符串,bytes.decode(encoding=编码格式,errors='strict')

a = b'hello world'
print(a)  # b'hello world'
print(type(a))  # <class 'bytes'>
# bytes类型也可以使用一些字符串的方法, 可以利用dir()函数查看所用相关方法
print(dir(bytes))
'''
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', 
'__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', 
'__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', 
'__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 
'capitalize', 'center', 'count', 'decode', 'endswith', 'expandtabs', 'find', 'fromhex', 'hex', 'index', 'isalnum', 
'isalpha', 'isascii', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 
'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 
'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
'''
# replace()
new_a = a.replace(b'h', b'aaa')  # 注意传的参数也要是比特类型
print(new_a)  # b'aaaello world'

# 比特数据中不能带中文,可以先将字符串转换下
# b = b'你好 world'  # SyntaxError: bytes can only contain ASCII literal characters.
# print(b)
b = '你好 world'
new_b = b.encode('utf-8')
print(new_b)  # b'\xe4\xbd\xa0\xe5\xa5\xbd world'

reduction_b = new_b.decode('utf-8')
print(reduction_b)  # 你好 world

 

4.列表、元组、集合间的转换

  直接调用相关内置函数即可;

  list()、tuple()、set()  

test_list = [34, 56]
tuple_test = tuple(test_list)
print(tuple_test)  # (34, 56)
print(type(tuple_test))  # <class 'tuple'>

new_tuple = (45,)
set_test = set(new_tuple)
print(set_test)  # {45}
print(type(set_test))  # <class 'set'>

print(list(set_test))  # [45]
print(type(list(set_test)))  # <class 'list'>

 

总结

  

标签:__,转换,python,数据类型,字符串,test,str,print
From: https://www.cnblogs.com/white-list/p/16813764.html

相关文章

  • python
    基础赋值打印word="""12345段落"""print(word[0:6])输出结果12345换行的话是空格字符不换行输出print('xyz',end="")print('dnf')......
  • Educational Codeforces Round 83 (Rated for Div. 2) C. Adding Powers(进制转换)
    https://codeforces.com/contest/1312/problem/C题目大意:给定一个长度为n的数组a,在给定一个底数k。一开始数组元素全部都是0,我们每一个时间i可以选择一个下标下的数字......
  • Python 发送邮件的几种情况
    本次记录一下Python发送邮件的几种情况:1、正常发送2、正文带图片3、正文带表格4、正文带附件 首先来看一下Python发送邮件使用到的模块##导入模块fromemail.mi......
  • python的高级特性-迭代概念
    迭代Python内置的enumerate函数可以把一个list变成索引-元素对,这样就可以在for循环中同时迭代索引和元素本身>>>fori,valueinenumerate(['A','B','C']):...prin......
  • Python pygame新手入门基础教程
    pygame简介 pygame可以实现python游戏的一个基础包。  pygame实现窗口 初始化pygame,init()类似于java类的初始化方法,用于pygame初始化。pygame.init()......
  • python中numpy切片问题
    方式1:逗号前表示行,冒号表示从该行的第几个到第几个(包含头不包含尾)方式2:逗号在后,表示列,冒号表示从该列的第几个到第几个(包含头不包含尾)......
  • python3学习笔记【简易】
    0.注意事项与码风修正1.注意到句尾分号没影响到编译,查资料知可加可不加,最好不加。当在一行中写多句代码时需要加。2.for循环和if/else句尾冒号前不要有空格! 1.操作种......
  • python抓取Prometheus的数据(使用prometheus-api-client库)
    python抓取Prometheus的数据(使用prometheus-api-client库)0、写在前面我们要想抓取Prometheus的数据,一般想到的就是requests请求,爬虫的方式来抓取,这是可行的,当然,还有一个......
  • Python应用框架一览表——敬请期待!
    Webflask、trondo、Django、GUIEasyGui、Tkinter框架、网络爬虫Scrapy框架Scrapy框架安装步骤:pipinstallscrapy使用Scrapy框架编写爬虫共计4步。数据分析re模......
  • 基于TensorFlow和Python的机器学习(笔记2)
    基于TensorFlow和Python的机器学习(笔记2)     油耗预测项目(实战)importioimportos.pathimportmatplotlib.pyplotaspltimportkeras.utilsimportte......