The most complete Python 3 type conversion guide in history

Source: Internet
Author: User
Tags eval

Int

Support is converted to type int, only, float , str bytes , and other types are not supported.

float-INT

The decimal point and subsequent values are removed, leaving only the integer part.

1 Int (-12.94) # -12
STR--INT

If there are characters other than the number (0-9) and the sign (+/-) in the string, an error will be found.

123 Int (' 1209 ') # 1209int (' -12 ') # -12int (' +1008 ') # 1008
Bytes-INT

If there are characters other than the number (0-9) and the sign (+/-) in the bytes, an error will be found.

123 Int (B ' 1209 ') # 1209int (B ' -12 ') # -12int (B ' +1008 ') # 1008

Float

Support conversion to float type, only,, int str bytes , and other types are not supported.

float, int

When int is converted to float, a decimal number is automatically added.

1 Float (-1209) # -1209.0
float, str

If the string contains a positive sign (+/-), a number (0-9), and a decimal point (.) The conversion is not supported for characters other than

12 Float (' -1209 ') # -1209.0float (' -0120.29023 ') # -120.29023
Bytes-Float

If the bytes contains a sign (+/-), a number (0-9), and a decimal point (.) The conversion is not supported for characters other than

12 Float (b ' -1209 ') # -1209.0float (b ' -0120.29023 ') # -120.29023
Complex

Only supported int , float str converted to complex types.

Complex int

When int converts complex, the imaginary part is automatically added and 0j represented.

1 Complex ( 12+0j)
Float-Complex

When float converts complex, the imaginary part is automatically added and 0j represented.

1 Complex (-12.09) # ( -12.09+0J)
STR--Complex

When STR converts complex, if it can be converted to int or float, it will convert to complex. A string can also be converted to a complex type value if it conforms exactly to the complex expression rule.

123456789 complex ( ' -12.09 ') # ( -12.09+0j) complex ( '-12.0 ') # ( -12+0j), removing the decimal part Complex ( ' -12 ') # ( -12+0j) complex ( ' -12+9j ') # ( -12+9j) complex ( (- 12+9j) ' # ( -12+9j) complex ( ' -12.0-2.0j ') # ( -12-2j), removed the decimal part complex ( ' -12.0-2.09j ') # ( -12-2.09j) complex (b ') # Error, does not support bytes conversion to complex complex (# error, There is no space on either side of the plus sign
Str

str()The function can convert any object to a string.

STR, int

The int conversion str will be converted directly and completely.

1 STR (+) #
float-Str

Float converts STR To remove the number of decimal points that are at the bottom of 0.

1 STR (-12.90) # -12.9
Complex-Str

Complex convert str, the value is converted to a standard complex expression before being converted to a string.

12 STR (Complex ( 9j)) # (12+9j)str (Complex ( 9)) # (12+9j)
Bytes-Str

The conversion between bytes and Str is a special point, in Python 3.x, strings and bytes are no longer confused, but are completely different data types.

Convert to an executable expression string:

1 STR (B ' Hello World ') # b ' Hello World '

str()The function specifies the encoding parameter, or uses the Bytes.decode () method to convert the actual data:

123 B ' Hello World '. Decode () # helloWorld str (B ' Hello World ', encoding=' Utf-8 ') # Hello world< /c5>str (B ' \xe4\xb8\xad\xe5\x9b\xbd ', encoding=' Utf-8 ') # China
List--Str

The value is formatted as a standard list expression before being converted to a string.

123 STR ([]) # []str ([1, 2, 3]) # [1, 2, 3]'. Join ([' a ', ' B ', ' C ']) # ABC
Tuple-Str

The value is formatted as a standard tuple expression before being converted to a string.

123 STR (()) # ()str ((1, 2, 3)) # (1, 2, 3)". Join (' a ', ' B ', ' C ') # ABC
Dict-Str

The value is formatted as a standard dict expression before being converted to a string.

123 Str ({' name ': ' hello ', ' age ': + }) # {' name ': ' Hello ', ' age ': +}str ({}) # {} '. Join ({' name ': ' hello ', ' age ': ' ) # nameage
Set-STR

The value is formatted as a standard set expression before being converted to a string.

123 STR (set ({})) # Set ()str ({1, 2, 3}) # {1, 2, 3}'. Join ({' a ', ' B ', ' C '}) # ABC
Other types

Convert built-in objects:

12 STR (int) # <class ' int ';, convert built-in class str (hex) # <built-in function Hex>, convert built-in functions

To convert a class instance:

123456789 class Hello: pass obj = Hello () print (str (obj)) # <__main__. Hello object at 0x1071c6630>

Conversion functions:

1234567 def Hello(): Pass print (str (hello)) # <function Hello at 0x104d5a048>
bytes

Only str convert to bytes type is supported.

123 ' China '. Encode () # b ' \xe4\xb8\xad\xe5\x9b\xbd ' bytes (' China ', encoding=' Utf-8 ') # b ' \xe4\xb8 \XAD\XE5\X9B\XBD '
List

Supports conversions to list types, only sequences, such as: STR, tuple, dict, set, and so on.

List by str
1 List (' 123abc ') # [' 1 ', ' 2 ', ' 3 ', ' A ', ' B ', ' C ']
List bytes

Bytes Conversion list, the ASCII decimal value of each byte is taken and combined into a list

1 List (B ' Hello ') # [104, 101, 108, 108, 111]
List by tuple

It is simpler to convert a tuple to a list.

1 List ((1, 2, 3)) # [1, 2, 3]
List Dict

Dictionary conversion list, which takes the key name as the value of the list.

1 List ({' name ': ' hello ', ' age ': + }) # [' Name ', ' age ']
List, set

The collection conversion list, which first goes back to the standard set value, and then transforms.

1 List ({1, 2, 3, 3, 2, 1}) # [1, 2, 3]
Tuple

As with lists, types that are converted to tuple are supported, only sequences.

STR--tuple
1 Tuple (' Chinese ') # (' Middle ', ' country ', ' person ')
Bytes-a tuple

Bytes converts a tuple, taking the ASCII decimal value of each byte and combining it into a list.

1 Tuple (B ' Hello ') # (104, 101, 108, 108, 111)
List-a tuple
1 Tuple ([1, 2, 3]) # (1, 2, 3)
Dict-A tuple
1 Tuple ({' name ': ' hello ', ' age ': + }) # (' Name ', ' age ')
Set-a tuple
1 Tuple ({1, 2, 3, 3, 2, 1}) # (1, 2, 3)
DICTSTR-Dict
  • Using the JSON module

    When using JSON modules to convert JSON strings into dictionaries, it is necessary to fully conform to the JSON specification, especially if the keys and values can only be wrapped in single quotes, otherwise an error will be made.

    123456 Import json user_info = ' {' name ': ' John ', ' gender ': ' Male ', ' age ':' print ' (Json.loads (user_info ) # {' Name ': ' John ', ' gender ': ' Male ', ' age ':-}
  • Use the eval function

    Because the eval function can execute any syntax-compliant expression string, there is a serious security issue and is not recommended.

    1234 user_info = "{' name ': ' John ', ' gender ': ' Male ', ' age ':" print (eval (user_info))  # {' name ': ' John ', ' gender ': ' Male ', ' age ': +}
  • Using the Ast.literal_eval method

    Using Ast.literal_eval for conversion does not have the problem of using JSON for conversion, and there is no security issue using Eval for conversion, so Ast.literal_eval is recommended.

    1234567 Import ast User_info = "{' name ': ' John ', ' gender ': ' Male ', ' Age ':"} "user_dict = ast.literal_eval (user _info) print (user_dict) # {' Name ': ' John ', ' gender ': ' Male ', ' age ':-}
List--Dict

Map 2 lists to a dictionary by Zip:

12345 List1 = [1, 2, 3, 4]list2 = [1, 2, 3]print (Dict (Zip ( List1, List2)) # {1:1, 2:2, 3:3}

To convert a nested list to a dictionary:

123456789 Li = [[1, 111],[2, 222],[3, 333],] Print (Dict (LI)) # {1:111, 2:222, 3:333}
Tuple--Dict

Map 2 tuples to a dictionary via zip:

123456 TP1 = (1, 2, 3)TP2 = (1, 2, 3, 4) print (dict (Zip (TP1, TP2) ) # {1:1, 2:2, 3:3}

To convert a nested tuple to a dictionary:

123456789 TP = ((1, 111),(2, 222), (3, 333),) print (DICT (TP)) # {1:111, 2:222, 3:333}
Set--Dict

Map 2 sets to a dictionary by Zip:

123456 Set1 = {1, 2, 3}Set2 = {' a ', ' B ', ' C '} print (dict (Zip (Set1, Set2)) # {1: ' C ', 2: ' A ', 3: ' B '}
SETSTR, set

The characters are first cut into tuples and then converted to collections.

1 Print (Set (' Hello ')) # {' L ', ' o ', ' e ', ' H '}
Bytes, set

The ASCII decimal value of each byte is taken and the Narimoto group is combined and then weighed.

1 Set (B ' Hello ') # {104, 108, 101, 111}
List--Set

First, the list to heavy, and then converted.

1 Set ([1, 2, 3, 2, 1]) # {1, 2, 3}
Tuple--Set

First, the list to heavy, and then converted.

1 Set ((1, 2, 3, 2, 1)) # {1, 2, 3}
Dict, set

The key names of the dictionaries are combined into collections.

123 Set ({' name ': ' hello ', ' age ': + }) # {' Age ', ' name '}

The most complete Python 3 type conversion guide in history

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.