What Xiaoting is sharing with you today is Python3 Conversion of common data types .
Python3 Conversion of common data types
Python3 Built in function data type conversion is commonly used in
function
explain
int(x [,base ])
take x Convert to an integer (x Is a string or number ,base Hexadecimal number , Default decimal Floating point to integer )
long(x [,base ])
take x Convert to a long integer
float(x )
take x Converts to a floating point number
complex(real [,imag ])
Create a complex number
str(x )
Put the object x Convert to string
repr(x )
Put the object x Converts to an expression string
eval(str )
Used to calculate the validity in a string Python expression , And returns an object
tuple(s )
The sequence of s Converts to a tuple
list(s )
The sequence of s Convert to a list
chr(x )
Converts an integer to a character
unichr(x )
Convert an integer to Unicode character
ord(x )
Converts a character to its integer value
hex(x )
Convert an integer to a hexadecimal string
oct(x )
Converts an integer to an octal string
4 The conversion of Radix to radix : adopt python Built in functions in (bin、oct、int、hex) To implement the transformation
List to set ( duplicate removal )
list1 = [6, 7, 7, 8, 8, 9] print(set(list1)) Python3 result :{6, 7, 8, 9}
Two lists go to the dictionary
list1 = ['key1','key2','key3'] list2 = ['1','2','3'] print(dict(zip(list1,list2))) Python3 result :{'key1': '1', 'key2': '2', 'key3': '3'}
Nested list to dictionary
list3 = [['key1','value1'],['key2','value2'],['key3','value3']] print(dict(list3)) Python3 result :{'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
list 、 Tuple to string
list2 = ['a', 'a', 'b'] print(''.join(list2)) Python3 result :aab tup1 = ('a', 'a', 'b') print(''.join(tup1)) Python3 result :aab
Dictionary to string
dic1 = {'a':1,'b':2} print(str(dic1)) Python3 result :{'a': 1, 'b': 2}
Dictionaries key and value Interturn
dic2 = {'a': 1, 'b': 2, 'c': 3} print({value:key for key, value in dic2.items()}) Python3 result :{1: 'a', 2: 'b', 3: 'c'}
String to list
s = 'aabbcc' print(list(s)) Python3 result :['a', 'a', 'b', 'b', 'c', 'c']
String to tuple
print(tuple(s)) Python3 result : ('a', 'a', 'b', 'b', 'c', 'c')
String conversion
print(set(s)) Python3 result :{'a', 'b', 'c'}
String to dictionary
s = "{'name':'Tom', 'age':18}" dic2 = eval(s) print(dic2) Python3 result :{'name': 'Tom', 'age': 18} a = '{"name":"Rose","age":19}' print(eval(a)) Python3 result :{'name': 'Rose', 'age': 19}
Welcome to xiaotinger's blog :https://blog.csdn.net/u010986753
DB Written interview history link
http://mp.weixin.qq.com/s/Vm5PqNcDcITkOr9cQg6T7w
● The author of this article : Xiaoting'er
● Author's blog address :https://blog.csdn.net/u010986753
● copyright , Welcome to share this article , Reprint please keep the source