1. Simple coercion
function format | Example of use | describe |
int(x [,base]) | int("8") | Convertible includes String type and other numeric types, but will lose precision |
float(x) | float(1) or float("1") | String and other numeric types can be converted, and the insufficient digits are filled with 0, for example, 1 will become 1.0 |
complex(real ,imag) | complex("1") or complex(1,2) | The first parameter can be a String or a number, the second parameter can only be a number type, and the default is 0 if the second parameter does not exist |
str(x) | str(1) | Convert number to String |
repr(x) | repr(Object) | Returns an object in String format |
eval(str) | eval("12+23") | Execute a string expression and return the result of the calculation, such as 35 in the example |
tuple(seq) | tuple((1,2,3,4)) | The parameter can be a tuple, a list or a dictionary. When wie a dictionary, it returns a set of keys of the dictionary. |
list(s) | list((1,2,3,4)) | Convert the sequence into a list. The parameters can be tuples, dictionaries, or lists. When it is a dictionary, it returns a set of keys of the dictionary. |
set(s) | set(['b', 'r', 'u', 'o', 'n'])或者set("asdfg") | Convert an iterable object into a mutable set, and de-duplicate, the returned result can be used to calculate difference x - y, union x | y, intersection x & y |
frozenset(s) | frozenset([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) | Convert an iterable object into an immutable collection, the parameters are tuples, dictionaries, lists, etc., |
chr(x) | chr(0x30) | chr() takes an integer in the range (256) (that is, 0 to 255) as a parameter, and returns a corresponding character. The return value is the ascii character corresponding to the current integer. |
word (x) | ord('a') | Returns the corresponding ASCII value, or Unicode value |
hex(x) | hex(12) | Convert an integer to a hexadecimal string |
oct(x) | oct(12) | Convert an integer to an octal string |
2. Other conversion methods
string to list
>>> str='python'
>>> str1='python'
>>> list1=list(str1)
>>> list1
['p', 'y', 't', 'h', 'o', 'n']
>>> list2=str1.split()
>>> list2
['python']
>>> str2=
File "<stdin>", line 1
str2=
^
SyntaxError: invalid syntax
>>> str3 = "www.google.com"
>>> list=str3.split('.')
>>> list
['www', 'google', 'com']
>>>
convert list to string
>>> list1=['a','b','c','d']
>>> str1=''.join(list1)
>>> str1
'abcd'
>>> str2='.'.join(list1)
>>> str2
'a.b.c.d'
>>> str2='. '.join(list1)
>>> str2
'a. b. c. d'
Convert list to dictionary
1.现在有两个列表,list1 = ['key1','key2','key3']和list2 = ['1','2','3'],把他们转为这样的字典:{'key1':'1','key2':'2','key3':'3'}
>>>list1 = ['key1','key2','key3']
>>>list2 = ['1','2','3']
>>>dict(zip(list1,list2))
{'key1':'1','key2':'2','key3':'3'}
2、将嵌套列表转为字典,有两种方法,
>>>new_list= [['key1','value1'],['key2','value2'],['key3','value3']]
>>>dict(list)
{'key3': 'value3', 'key2': 'value2', 'key1': 'value1'}
或者这样:
>>>new_list= [['key1','value1'],['key2','value2'],['key3','value3']]
>>>new_dict = {}
>>> for i in new_list:
... new_dict[i[0]] = i[1] #字典赋值,左边为key,右边为value
...
>>> new_dict
{'key3': 'value3', 'key2': 'value2', 'key1': 'value1'}
>>> new_list= [['key1','value1'],['key2','value2'],['key3','value3']]
>>> for i in new_list:
... new_dict={}
... new_dict[i[0]]=i[1]
...
>>> new_dict
{'key3': 'value3'}
Convert dictionary to list
①转换后的列表为无序列表
a = {'a' : 1, 'b': 2, 'c' : 3}
#字典中的key转换为列表
key_value = list(a.keys())
print('字典中的key转换为列表:', key_value)
#字典中的value转换为列表
value_list = list(a.values())
print('字典中的value转换为列表:', value_list)
运行结果:
②转换后的列表为有序列表
import collections
z = collections.OrderedDict()
z['b'] = 2
z['a'] = 1
z['c'] = 3
z['r'] = 5
z['j'] = 4
#字典中的key转换为列表
key_value = list(z.keys())
print('字典中的key转换为列表:', key_value)
#字典中的value转换为列表
value_list = list(z.values())
print('字典中的value转换为列表:', value_list)
Convert between dictionary and string
#字典转换成字符串
json.dumps(dict1)
>>> import json
>>> str2=json.dumps(dict1)
>>> str2
'{"key2": "value3", "key1": "value1", "key": "value"}'
>>>
str(dict1)
>>> str3=str(dict1)
>>> str3
"{'key2': 'value3', 'key1': 'value1', 'key': 'value'}"
>>>
#字符串转换成字典