各种数据类型间的转换

2022-12-21 Python基础

Python中定义变量不需要指定数据类型,但同样需要用到数据类型之间的转换。本文会介绍在Python中字符串与数字、字符串与列表、字符串与Bytes类型以及集合、列表、元组之间的转换。

# 1.字符串与数字

转换 函数 举例
int→str str s = str(123456)
float→str str s = str(3.14)
str→int int m = int('12')
str→float float n = float('1.2')

# 2.字符串与列表直接的转换

  • 字符串转列表:split(sep=None, maxsplit=-1)
    • sep:切割的符号,默认以空格切割
    • maxsplit:根据切割符号切割的次数,默认-1表示无限制
  • 列表转字符串:'sep'.join(iterable)
    • sep:生成字符串用来分隔列表每个元素的符号
    • iterable:非数字类型的列表或元组或集合
if __name__ == '__main__':
    st = '张三,李四,王五'
    list1 = st.split(',')  # 指定以逗号进行切割,默认使用空格切割字符串
    print(list1)            # ['张三', '李四', '王五']
    
    print(' '.join(list1))  # 张三 李四 王五

# 3.bytes(比特类型)

byte继承了字符串的大部分方法,Python定义bytes变量的方法:

if __name__ == '__main__':
    st = b'zhangsan'
    print(type(st))  # <class 'bytes'>
    print(st)        # b'zhangsan'

# 4.字符串与Bytes类型转换

  • 字符串转bytes:str.endcode(encoding='utf8',errors='strict')
    • encoding:转换成的编码格式
    • errors:出错的处理方法,默认strict直接抛出错误,也可选择ignore忽略错误
    • 返回值:返回一个bytes类型
  • bytes转字符串:bytes.decode(encoding='utf8',errors='strict')
if __name__ == '__main__':
    st = 'zhangsan'
    by = st.encode()    # 字符串转bytes
    print(by)           # b'zhangsan'
    print(by.decode())  # zhangsan,bytes转字符串

# 5.集合、列表、元组之间的转换

转换 函数 举例
列表→集合 set new_set = set([1, 2, 3])
列表→元组 tuple new_tuple = tuple([1, 2, 3])
元组→集合 set new_set = set((1, 2, 3))
元组→列表 list new_list = list((1, 2, 3))
集合→列表 list new_list = list({1, 2, 3})
集合→元组 tuple new_tuple = tuple({1, 2, 3})
上次更新: 1 年前