str1 = "string"
list1 = list(str1)
print(list1)
str2 = "i am ybc"
list2 = str2.split()
print(list2)
str3 = "www.google.com"
list3 = str3.split(".")
print(list3)
#运行结果
['s', 't', 'r', 'i', 'n', 'g']
['i', 'am', 'ybc']
['www', 'google', 'com']
str4 = "".join(list1)
print(str4)
str5 = " ".join(list2)
print(str5)
str6 = ".".join(list3)
print(str6)
#运行结果
string
i am ybc
www.google.com
将字符串str当成有效的表达式来求值并返回计算结果
无法处理多维字典;字符串里面的字符必须是单引号
user = "{'name' : 'zhangsan', 'sex' : 'male', 'age': 20}"
dict1 = eval(user)
print(dict1)
#运行结果
{'name': 'zhangsan', 'sex': 'male', 'age': 20}
字符串里面的字符必须是双引号
import json
user = '{"name":"zhangsan","sex":"male","age":"20"}'
dict2 = json.loads(user)
print(dict2)
#运行结果
{'name': 'zhangsan', 'sex': 'male', 'age': '20'}
dict = {'name': 'zhangsan', 'sex': 'male', 'age': '20'}
str = str(dict)
print(type(str), str)
#运行结果
<class 'str'> {'name': 'zhangsan', 'sex': 'male', 'age': '20'}
import json
dict = {'name': 'zhangsan', 'sex': 'male', 'age': '20'}
str = json.dumps(dict)
print(type(str), str)
#运行结果
<class 'str'> {"name": "zhangsan", "sex": "male", "age": "20"}
list函数默认是将字典中的key取出来,返回list
dict = {'name': 'zhangsan', 'sex': 'male', 'age': '20'}
#字典中的key转换为列表
list1 = list(dict.keys())
#字典中的value转换为列表
list2 = list(dict.values())
print(list1, list2)
#运行结果
['name', 'sex', 'age'] ['zhangsan', 'male', '20']
dict = {'name': 'zhangsan', 'sex': 'male', 'age': '20'}
list_key = []
list_value = []
for key, value in dict.items():
list_key.append(key)
list_value.append(value)
print(list_key, list_value)
#运行结果
['name', 'sex', 'age'] ['zhangsan', 'male', '20']
list = ['zhangsan', '18']
dict = {}
for i in range(len(list)):
dict[i] = list[i]
print(dict)
#运行结果
{0: 'zhangsan', 1: '18'}
python的元组与列表类似,但元组的元素不能修改
str转化为tuple,直接进行转换
str = "zhangsan 18"
tuple = tuple(str)
print(tuple)
#运行结果
('z', 'h', 'a', 'n', 'g', 's', 'a', 'n', ' ', '1', '8')
str = "zhangsan 18"
tuple = tuple(str.split())
print(tuple)
#运行结果
('zhangsan', '18')
tuple转换为str需要借助join()函数来实现
tuple = ('z', 'h', 'a', 'n', 'g', 's', 'a', 'n', ' ', '1', '8')
str = "".join(tuple)
print(str)
#运行结果
zhangsan 18
list = ['zhangsan', '18']
tuple = tuple(list)
print(tuple)
#运行结果
('zhangsan', '18')