Python_字符类型转换

split

将str以某个字符分割成list

_str1 = "a.b.c"
_str2 = "a/b/c"

_list1 = _str1.split(".")
_list2 = _str2.split("/")
print(_list1, _list2)

join

将list以某个符号拼接成string

_list = ["a", "b", "c"]

# 以"."拼接列表所有值
_str1 = ".".join(_list)

# 以"/"拼接列表所有值
_str2 = "/".join(_list)
print(_str1, _str2)

dict

将两位长度的元祖组成的list转换为字典

a = ["a", "b", "c"]
b = [1, 2, 3]

tup = zip(a, b)
print(tup)
d = dict(tup)
print(d)

json字符串与python类型相互转化

json 类型与python类型对照表:

JSONPython
object dict
array list
string unicode
number (int) int, long
number (real) float
true True
false False
null None

json.loads将json字符串转换为python类型

将json的object类型转换为python的dict类型

import json

# 定义json字符串,注意键值均用双引号,否则在转换成是会报错
json_string = '{"name": "张三", "age": 18}'

# 将json字符串转换为dict
ts_dict = json.loads(json_string)
print(type(json_string), type(ts_dict), ts_dict)

需要注意的是,转换的字符串需要符合json字符的规范,比如,键值需用双引号,否则在转换时会抛 Expecting property name 的错误。

比如如下范例就会报错

# 定义json字符串,注意键值均用双引号,否则在转换成是会报错
json_string = "{'name': '张三', 'age': 18}"

# 将json字符串转换为dict
ts_dict = json.loads(json_string)
print(type(json_string), type(ts_dict), ts_dict)

 我们可以使用eval内置函数进行转换

# 定义json字符串,注意键值均用双引号,否则在转换成是会报错
json_string = "{'name': '张三', 'age': 18}"

# 将json字符串转换为dict
ts_dict = eval(json_string)
print(type(json_string), type(ts_dict), ts_dict)

 json.dumps将dict转换成json字符串

import json

# 定义dict类型数据
_dict = {"name": "张三", "age": 18}

# 将dict转换成json。ensure_ascii:不将中文以ascii转换
ts_string = json.dumps(_dict, ensure_ascii=False)
print(type(_dict), type(ts_string), ts_string)

 

posted @ 2021-02-21 19:17  码上测  阅读(179)  评论(0编辑  收藏  举报