python中各数据类型的转换-整型/浮点型/str型/char型/list型/dict型

str -> int/float/list

# 整型数字的字符串转化为数字 int/float
strInt = "123"
# str -> int
strInt2Int = int(strInt)
# str -> float
strInt2Float = float(strInt)

# 小数的字符串转化为数字 int/float
strFloat = '12345.678'
# str -> int, 截断小数部分,保留整数部分
strFloat2Int = int(float(strFloat))
# str -> float
strFloat2Float = float(strFloat)

#****************#

num -> str

# int -> str
Int2String = str(123)
# float -> str
float2String = str(123.45)

str <-> list

# str -> list
strFloat2List = list(strFloat)

print(strFloat, strFloat2Int, strFloat2Float, strFloat2List)

# list -> str
# list必须是str类型的数组
list2String = ''.join(['1', '2', '3', '4', '5', '.', '6', '7', '8'])

char <-> num

# char or byte -> num
char2Int = ord('a')
print(char2Int) # 97
char2Int = ord('A')
print(char2Int) # 65
char2Int = ord('1')
print(char2Int) # 49

# num -> char
num2Char = chr(97)
print(num2Char)
num2Char = chr(65)
print(num2Char)
num2Char = chr(49)
print(num2Char)

str <-> dict

# 1. json
import json
jsonStr = '{"name" : "john", "gender" : "male", "age": 28}'
jsonStr2Dict = json.loads(jsonStr)
print(jsonStr2Dict, type(jsonStr2Dict))
# {'name': 'john', 'gender': 'male', 'age': 28} <class 'dict'>
dict2Json = json.dumps(jsonStr2Dict)
print(dict2Json, type(dict2Json))
# {"name": "john", "gender": "male", "age": 28} <class 'str'>

# 2.eval
str2Dict = eval('{"name" : "john", "gender" : "male", "age": 28}')
print(str2Dict, type(str2Dict))
# {'name': 'john', 'gender': 'male', 'age': 28} <class 'dict'>

# 3. ast
import ast
str = "{'name': 'john', 'gender': 'male', 'age': 28}"
str2Dict = ast.literal_eval(str)
print(str2Dict, type(str2Dict))
# {'name': 'john', 'gender': 'male', 'age': 28} <class 'dict'>

posted on 2022-01-18 16:39  进击的davis  阅读(1191)  评论(0编辑  收藏  举报

导航