Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to convert between different data types of Python

2025-01-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces the relevant knowledge of how to convert between different data types of Python, the content is detailed and easy to understand, the operation is simple and fast, and it has a certain reference value. I believe you will have something to gain after reading this article on how to convert between different data types of Python. Let's take a look.

Conversion between string and numeric type

What is type conversion? -> the process of changing your own data type into a new data type and having all the functions of the new data type is type conversion

Why do type conversions? -> in order to facilitate and better help with the business, change the type to one that is more suitable for the business scenario

For example, a ='1', which is a string type, so it cannot perform numeric operations.

Requirements for conversion between strings and numbers

Str-> number: must be a string of numbers before it can be converted to a numeric type through type conversion

Int_str = '1024'; float_str = '3.1415926'

Number-> str: no requirements

Conversion function between string and number primitive type target type function example integer string strnew_str = str (123456) floating point string strnew_str = str (3.1515926) string integer intnew_int = int ('1234') string floating point intnew_float = int (' 3.1415926')

Examples are as follows:

Str_int = '1024'new_int = int (int_str) print (new_int) # execution result is as follows: # > 102 strings > > int_str = 3.1415926new_str = str (int_str) print (new_str) print (type (new_str)) # execution results are as follows: # > 3.141592characters > int_and_str =' 123abc' # only numeric strings can be used Convert to numeric type new_int = int (int_and_str) print (new_int) # through type conversion: # > ValueError: invalid literal for int () with base 10: conversion between '123abc' string and list split () function-string transfer list

The function of the split () function is to cut strings according to certain rules and convert them into lists.

Usage of split () function: string.split (sep=Node, maxsplit=-1)

Sep: as a regular symbol for cutting recognition, the default cutting rule symbol is a space if it is not filled in; if there is no space in the string, it is not divided into a list.

Maxsplit: the number of times a string is cut with a cutting rule symbol, which defaults to-1, that is, the number of times is unlimited.

The return value of the split () function is a list

Examples are as follows:

Name ='My name is Neo'name_list = name.split () print (name_list) # the execution result is as follows: # > ['My',' name', 'is',' Neo'] # > you can see that 'name' has been cut with a space as a regular symbol into a list of elements test_int =' 1, 2, 3, 4'test_int_list = test_int.split ('' ') print (test_int_list) # the execution result is as follows: # > > [' 1percent, '2percent,' 3percent,'4'] # > > you can see that 'test_int' has been cut with a comma as a cutting rule symbol into a list of elements test_str =' a | b | c | d | e'test_str_list = test_str.split ('|' 2) the execution result of print (test_str_list) # is as follows: # > ['averse,' b' 'c | d | e'] # > > you can see that' test_str_list' 'has been cut twice with' |'as the cutting rule symbol error_str = 'a~b~c' test_error_str = error_str.split ('') print (test_error_str) # the execution result is as follows: # > ValueError: empty separator Note: the split () function cannot use an empty string as a cutting rule character. The join () function of the number-list to string

The function of the split () function is to cut the list according to certain rules and convert it into a string.

Usage of the split () function: 'sep'.join (iterable)

Sep: the symbol used to generate a string to split each element of the list

Iterable: a list or tuple or collection of non-numeric types

The return value of the join () function is a string

It is important to note that the list can be converted to a string only if the list element is a string, and an error will be reported if the list element is a number, tuple, dictionary, and other data types.

Examples are as follows:

Test_info = ['a', 'baked,' c'] new_info ='- .join (test_info) print (new_info) # the execution result is as follows: # > a-b-ctest_info_int = [1,2,3,4] new_info_int ='- .join (test_info_int) print (new_info_int) # the execution result is as follows: # > > TypeError: sequence item 0: expected str instance, int foundtest_info_tuple = [(1,) (2, 3, 4)] new_info_tuple='- '.join (test_info_tuple) print (new_info_tuple) # the execution result is as follows: # > TypeError: sequence item 0: expected str instance, int found data type conversion-small exercise

Convert the string'an e f h j k d l' to a list and sort it, and then convert it to a string.

The code example is as follows:

Sort_str ='an e f h j k d l'sort_str_list = sort_str.split ('') print (sort_str_list) # the execution result is as follows: # > ['asides,' eBay, 'fallows,' hashes, 'jacks,' kills, 'dudes,' l'] sort_str_list.sort () print (sort_str_list) # the execution results are as follows: # > ['asides,' dudes,'e' The results are as follows: # > a | d | e | f | h | j | k | k | l # > > extension-sorted () function

The sorted () function is different from the sort () function. The sort () function is the built-in function of the list, while the sorted () function is the built-in function of python, which can handle all data types.

Examples are as follows:

The execution result of sort_str_new = 'aefhjkdc'result = sorted (sort_str_new) print (result) # is as follows: # > [' a string, 'cession,' dink, 'eBay,' fallow, 'hink,' jink,'k'] print ('. Join (result)) # the result is as follows: # > > acdefhjk string and bytes are converted by codec

What is bytes? (bit type)-> bytes is a binary data stream and a transportable type that exists in all programming languages. It can also be thought of as a special string because it looks almost exactly like a string and has almost all the built-in functions of the string. We can manipulate the bit type (bytes) like a string, except that the string needs to be preceded by a b flag.

Examples are as follows:

Bt = b'my name is Neo'print (the value of'\'bt\'is:', bt,'; the type of\'bt\'is:', type (bt)) # the execution result is as follows: # > 'bt': b'my name is Neo' The type of bt' is: print (bt.capitalize ()) # the execution result is as follows: # > b'My name is neo'print (bt.replace ('Neo',' Jack')) # the execution result is as follows: # > TypeError: a bytes-like object is required, not 'str' the error is reported here because the type we replaced is a string type The correct way to write it is as follows: print (bt.replace (baked Neo') The execution result is as follows: # > > b'my name is Jack'print (bt [0]) print (bt [- 1]) print (bt [3:8]) # > > 109 is the display mode of'n 'binary stream # > 111The display mode of binary stream is' o' binary stream # > b'name The index position of the 'print ('\'N\ 'character is:' The result of bt.find (bounded N') # execution is as follows: # >'N' character index position is: 11test_info = b'my name is\'Li Lei\''print (test_info) # execution result is as follows: # > SyntaxError: bytes can only contain ASCII literal characters. # error message is "bytes" type only supports ASCII characters # which also leads to the following encode () function and decode () function encode () function-string to bytes

The function of the encode () function: to convert a string to a byte type

Usage of the encode () function:

Usage: string.encode (encoding='utf-8', errors='strict')

Parameters: encoding and errors

The encoding format converted by encoding, such as ascii, gbk, defaults to 'utf-8'

The method to handle errors error. Default is strict. If you report an error directly, you can also choose ignore error.

The return value is of a bytes type

Examples are as follows:

Test_str ='my name is HanMeimei'bytes_str = test_str.encode ('utf-8') print (bytes_str) print (type (bytes_str)) # the execution result is as follows: # > b'my name is HanMeimei'# > decode () function-bytes transfer string

The function of the decode () function: convert bit (byte) type to string

Usage of the decode () function:

Usage: string.encode (encoding='utf-8', errors='strict')

Parameters: encoding and errors; note that the encoding here is the role of decoding, and the encoding of the encode () function is the role of encoding.

The encoding format converted by encoding, such as ascii, gbk, defaults to 'utf-8'

The method to handle errors error. Default is strict. If you report an error directly, you can also choose ignore error.

The return value is of a string type

Examples are as follows:

Bytes_str = b'Python is very good'test_str = bytes_str.decode ('utf-8') print (test_str) print (type (test_str)) # execution result is as follows: # > Python is very good# > str_date =' my name is\ 'Adam\' byte_date = str_date.encode ('utf-8') print (byte_date) # execution result is as follows: # > b "my name is'\ xe4\ xba\ x9a\ Xe5\ xbd\ x93' "this is what utf-8 transformed into Chinese print (byte_date.decode ('utf-8')) # the execution result is as follows: # > my name is' Adam 'list, Collection, tuple conversion list function primitive type target type function example list collection setnew_set = set ([1] 2, 3, 4, 5]) list tuple tuplenew_tuple = ([1,2,3,4,5] tuple collection setnew_set = set ((1,2,3,4,5)) tuple list listnew_set = set ((1,2,3,4,5)) collection list listnew_list = list ({1,2,3,4,5}) collection tuple tuplenew_tuple = tuple ({1,2,3,4,5}) 5}) this is the end of the article on "how to convert different data types in Python" Thank you for reading! I believe you all have a certain understanding of the knowledge of "how to convert between different data types of Python". If you want to learn more, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report