Home > Backend Development > Python Tutorial > How to convert data types in python

How to convert data types in python

Release: 2019-07-01 13:46:47
Original
5237 people have browsed it

How to convert data types in python

When processing data, it is often necessary to convert the format of the data to facilitate operations such as data traversal. Let's take a look at several data type conversions in Python.

1. Convert string to dictionary:

dict_string = "{'name':'linux','age':18}"
to_dict = eval(dict_string)
print(type(to_dict))
Copy after login

You can also use json for conversion

import json #如果是Python2.6应该是simplejson
dict_string = "{'name':'linux','age':18}"
to_dict = json.loads(dict_string.replace("\‘","\“")) #这里需要将字符串的单引号转换成双引号,不然json模块会报错的
print(type(to_dict))
Copy after login

2. Convert dictionary to string

Similarly You can use json

import json
dict_1 = {'name':'linux','age':18}
dict_string = json.dumps(dict_1)
print(type(dict_string))
Copy after login

Of course, you can also directly use str to force conversion

dict_1 = {'name':'linux','age':18}
dict_string = str(dict_1)
print(type(dict_string))
Copy after login

3. String to list

Specify the delimiter

string1 = "1,2,3,4,5,'aa',12"
print(type(string1.split(',')))
Copy after login

If it is already List format, just use eval directly

string2 = "[1,2,3,4,5,'aa',12]"
print(type(eval(string2)))
Copy after login

4. Convert list to string

Use str directly to force conversion

print(type(str([1, 2,3,4,5,'aa',12])))

Specify the separator. Note that the lists here need to be of string type, otherwise an error will be reported during splicing

print(type("--".join(['a','b','c'])))

5. Convert list to dictionary

Two List, list1 = ['k1','k2','k3'], list2 = [1,2,3], converted into dictionary {'k1':1,'k2':2,'k3':3}

list1 = ['k1','k2','k3']
list2 = [1,2,3]
print(dict(zip(list1,list2)))
Copy after login

For more Python-related technical articles, please visit the Python Tutorial column to learn!

The above is the detailed content of How to convert data types in python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template