目录
一、整数与字符串的转换
1、整数与字符串的转换
number = 2
char = str(number)
int_char = int(char)
print(char, type(char)) # 输出:2 <class 'str'>
print(int_char, type(int_char)) # 输出:2 <class 'int'>
2、进制转换
二、字符串与列表的转换
1、字符串转列表(字符列表)
使用list()函数,会将字符串中的字符一一拆分成列表元素。
str1 = "hello world"
list1 = list(str1)
print(list1) # ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
2、列表转字符串
(1)列表中的元素都为字符串
使用 'sep'.join(seq) 函数,‘’中的sep为分隔符,()中的seq为需要连接的对象。要将列表转换为字符串,此时的列表需为字符串的列表。
list1 = ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
print(''.join(list1)) # hello world
或者:
list1 = ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
str1 = ''
for char1 in list1:
str1 += char1
print(str1) # 输出:hello world
(2)列表中的元素都为整数
先将列表中的整数转换为字符串即可。
digits = [1,2,3]
for i in range(0,len(digits)):
digits[i] = str(digits[i])
# 也可以list_digits = list(map(lambda x:str(x), digits))
# print(list_digits) # 输出:['1', '2', '3']
str_digits = ''.join(digits)
print('str_digits:', str_digits, type(str_digits))
# 输出:str_digits: 123 <class 'str'>
三、字符串与字典的转换
1、字符串转字典
2、字典转字符串
直接用str()
本人新手,若有错误,欢迎指正;若有疑问,欢迎讨论。若文章对你有用,点个小赞鼓励一下,谢谢,一起加油吧!