Python from small white to Daniel 6th data types

Source: Internet
Author: User
Tags control characters

Data types are used when declaring variables, and some data types, such as integers and strings, are used earlier. All data types in Python are classes, and each variable is an "instance" of the class. There is no concept of a basic data type, so integers, floats, and strings are also classes.

Python has 6 standard data types: numbers, strings, lists, tuples, collections, and dictionaries, lists, tuples, collections, and dictionaries can hold multiple data, each of which is a data structure that is collectively referred to as the "data structure" type.

This chapter introduces numbers and strings, which are described in detail later in the chapters, lists, tuples, collections, and dictionary data types.

Number Type

There are 4 types of Python numbers: integer type, float type, complex type, and Boolean type. It is important to note that the Boolean type is also a numeric type, which is actually one of the integer types.

Integer type

The python integer type is int, the range of integer types can be large and can represent a large integer, which is limited only by the hardware of the computer where it resides.

Tips for Python 2 python
3 no longer distinguishes between integers and long integers, as long as you want all integers to be long integers.

By default, an integer value, such as a decimal integer of 16, is represented. Then other binaries, such as binary numbers, octal numbers, and hexadecimal integers, are represented as follows:

    • Binary number: 0b or 0 B as a prefix, note that 0 is an Arabic numeral, do not mistakenly believe that the English letter O.

    • Octal number, prefixed with 0o or 0O, the first character is the Arabic numeral 0, the second character is the English letter O or O.

    • Hexadecimal number: prefixed with 0x or 0X, note that 0 is an Arabic numeral.

For example, integer values 28, 0b11100, 0b11100, 0o34, 0o34, 0x1c, and 0x1c all have the same number. In Python
The shell output results are as follows:

>>> 2828>>> 0b1110028>>> 0O3428>>> 0o3428>>> 0x1C28>>> 0X1C28
Floating-point types

Floating-point types are primarily used to store decimal values, and Python floating-point types Float,python only support double-precision floating-point types, and are native-related.

Floating-point types can be represented by decimals, or by scientific notation, which uses uppercase or lowercase e for the 10 exponent, such as E2 for 102.

Run the example in the Python shell as follows:

>>> 1.01.0>>> 0.00.0>>> 3.36e2336.0>>> 1.56e-20.0156

3.36e2 of them indicate that 3.36x102,1.56e-2 is 1.56x10-2.

Plural type

Complex numbers are very important concepts in mathematics, both in theoretical physics and in electrical engineering practice. But many computer languages do not support complex numbers, and Python supports complex numbers, which makes Python a good way to perform scientific calculations.

The plural type in Python is complex, for example 1+2j represents the complex number of real part 1, imaginary Part 2. In Python
The example running in the shell is as follows:

>>> 1+2j(1+2j)>>> (1+2j) + (1+2j)(2+4j)

The code above implements the addition of two complex numbers (1+2J).

Boolean type

The Boolean type in Python is Bool,bool, which is a subclass of int, and it has only two values: True and False.

Attention
Any type of data can be converted to a Boolean value through the bool () function, and those values that are considered "not", "empty", are converted to false, and vice versa to true. Values such as none (Empty object), False, 0, 0.0, 0j (plural), "(empty string), [] (Empty list), () (empty tuple), and {} (empty dictionary) are converted to False, otherwise true.

Examples are as follows:

>>> bool(0)False>>> bool(2)     True>>> bool(1)True>>> bool(‘‘)False>>> bool(‘  ‘)True>>> bool([])False>>> bool({})False

True for the output of the bool (2) and bool (1) Expressions in the code above, which means that both 2 and 1 can be converted to ture, and that only 0 in integers is converted to false, as are other types.

Conversion of numeric types to each other

After learning the previous data types, you will think of a question, can the data types be converted? Python has a number of functions that enable conversion between different data types. Such as: conversions between numeric types and conversions between integers and strings. This section first discusses the conversion of numeric types to each other.

In addition to complex numbers, the other three numeric types integer, floating point, and Boolean can be converted to each other, with conversions divided into implicit type conversions and explicit type conversions.

Implicit type conversions

There can be mathematical calculations between multiple numeric type data, and implicit type conversions occur because the number types involved in the calculation may be different. Implicit type conversion rules are shown in table 6-1 during the calculation.

Table 6?1 Implicit type-conversion rules

operand 1 Type operand 2 Type the converted type
Boolean Integer Integer
Boolean, Integer Floating point Floating point

Boolean values can be implicitly converted to an integer type, Boolean true converts to an integer 1, and a Boolean value of false converts an integer 0. In Python
The example running in the shell is as follows:

>>> a = 1 + True>>> print(a)2>>> a = 1.0 + 1>>> type(a)         ①<class ‘float‘>>>> print(a)2.0>>> a = 1.0 + True>>> print(a)2.0>>> a = 1.0 + 1 + False>>> print(a)2.0

From the type of operation result of the above code expression, the type conversion rule shown in table 6-1 is not mentioned here. In addition, the above code, line ①, uses the type () function,
The type () function can return the types of incoming data, and the \<class ' float ' \> description is a floating-point type.

An explicit type conversion

In cases where implicit conversions cannot be performed, the conversion function can be used for explicit conversions. In addition to complex numbers, three numeric type integers, floats, and Booleans have their own conversion functions, namely int (), float (), and bool () functions, and the bool () function is described in 6.1.4.

the int () function converts Boolean, floating-point, and string to integers. Boolean value true uses the Int () function to return 1,false using the Int () function to return 0, and a floating-point value that uses the Int () function to truncate the fractional part. the int () function conversion string is described in the next section.

The float () function converts booleans, integers, and strings to floating-point. Boolean value true use the float () function to return 1.0,false using the float () function to return 0.0; integer values use the float () function to add a fractional portion (. 0). The float () function conversion string is described in the next section.

Run the example in the Python shell as follows:

>>> int(False)0>>> int(True)1>>> int(19.6)19>>> float(5)5.0>>> float(False)0.0>>> float(True)1.0
String type

A sequence of characters consisting of characters, called "strings," where the strings are sequential, from left to right, and the index is incremented from 0. The string type in Python is str.

String representation

There are three ways to represent a string in Python:

    • Normal string. A string wrapped in single quotation marks (') or double quotation marks (").

    • Raw String (raw
      String). With R in front of the normal string, special characters in the string do not need to be escaped, and are rendered as if the string were "face".

    • Long string. The string contains typographic characters such as newline indentation, which can be wrapped with a triple single quotation mark ("') or triple double quotation mark (" "), which is a long string.
    1. Normal string

Many programmers are accustomed to using single quotation marks (') to denote strings. The following example shows the Hello World string:

‘Hello World‘"Hello World"‘\u0048\u0065\u006c\u006c\u006f\u0020\u0057\u006f\u0072\u006c\u0064‘    ①"\u0048\u0065\u006c\u006c\u006f\u0020\u0057\u006f\u0072\u006c\u0064"    ②

Characters in Python are Unicode encoded, so the string can contain Asian characters such as Chinese. The string in line ① and line ② of the code is a Unicode-encoded string, in fact it represents a hello
World string, you can output a Unicode-encoded string to the console through the print function and you will see Hello
World String. Run the example in the Python shell as follows:

>>> s = ‘Hello World‘>>> print(s)Hello World>>> s = "Hello World">>> print(s)Hello World>>> s = ‘\u0048\u0065\u006c\u006c\u006f\u0020\u0057\u006f\u0072\u006c\u0064‘>>> print(s)Hello World>>> s = "\u0048\u0065\u006c\u006c\u006f\u0020\u0057\u006f\u0072\u006c\u0064">>> print(s)Hello World

If you want to include some special characters in the string, such as line breaks, tabs, etc., you need to escape in a normal string, preceded by a backslash (\), which is called character escaping. Table 6-2 shows a few of the commonly used escape characters.

Table 6?2 Escape character

character Representation Unicode encoding Description
\ t \u0009 Horizontal tab
\ n \u000a Line break
\ r \u000d Enter
\" \u0022 Double quotes
\‘ \u0027 Single quotation marks
\\ \u005c Reverse Slash

Run the example in the Python shell as follows:

>>> s = ‘Hello\n World‘>>> print(s)Hello World>>> s = ‘Hello\t World‘>>> print(s)Hello    World>>> s = ‘Hello\‘ World‘>>> print(s)Hello‘ World>>> s = "Hello‘ World"  ①>>> print(s)Hello‘ World>>> s = ‘Hello" World‘      ②>>> print(s)Hello" World>>> s = ‘Hello\\ World‘ ③>>> print(s)Hello\ World>>> s = ‘Hello\u005c World‘ ④>>> print(s)Hello\ World

For single quotation marks (') and double quotation marks (") in a string, you can also do not escape the character, enclose the string in double quotation marks in a string containing single quotation marks, see line ① of code, and enclose the string in single quotation marks in a string containing double quotation marks, see Code line ②. In addition, you can use Unicode encoding to replace special characters that need to be escaped, and the code ④ line is equivalent to code section ③.

    1. Raw strings (Raw string)

Precede the normal string with the letter R, which indicates that the string is the original string, and the original string is used directly in the literal sense of the string, with no escape character. In Python
Run the sample code in the shell as follows:

>>> s = ‘Hello\tWorld‘  ①>>> print(s)Hello   World>>> s = r‘Hello\tWorld‘  ②>>> print(s)Hello\tWorld

Code ① is a normal string, the code ② is the original string, their difference is just the letter R in front of the string. As seen from the output, \ t in the original string is not used as a tab.

    1. Long string

A long string can be used if the string contains typographic characters such as newline indentation. In Python
Run the sample code in the shell as follows:

>>> s  =‘‘‘Hello World‘‘‘>>> print(s)Hello World>>> s = """ Hello \t            ①        World""">>> print(s) Hello          World

If you include special characters in a long string, you also need to escape it, see line ① of code.

String formatting

During the actual programming process, it is often encountered to stitch other types of variables together with strings and format the output. For example, the calculated amount needs to be preserved after the decimal point four, the number needs to be right-aligned, and so on, all of which need to be formatted.

You can use the format () method of the string as well as the placeholder when the string is formatted. In Python
The example running in the shell is as follows:

>>> name = ‘Mary‘>>> age = 18>>> s = ‘她的年龄是{0}岁。‘.format(age)        ①>>> print(s)她的年龄是18岁。>>> s = ‘{0}芳龄是{1}岁。‘.format(name, age) ②>>> print(s)Mary芳龄是18岁。>>> s = ‘{1}芳龄是{0}岁。‘.format(age, name) ③>>> print(s)Mary芳龄是18岁。>>> s = ‘{n}芳龄是{a}岁。‘.format(n=name,  a=age)    ④>>> print(s)Mary芳龄是18岁。

The string can have placeholders (the contents of {}), which, in conjunction with the format () method, replace the placeholder contents with the parameters in the format () method. Placeholders can be represented by a parameter index, see line ①, line ②, and line ③, or use the name of the parameter to represent a placeholder, see Code ④, N and a are parameter names.

Placeholders can also have formatting controls to more precisely control the format of strings. Different data types require different control characters for formatting, as shown in table 6-3.

Table 6?3 string Formatting control characters

Control character Description
S String formatting
D Decimal integer
F, F Decimal floating-point number
G, G Decimal integer or floating-point number
E, E Scientific calculation means floating-point number
O octal integer, symbol is small English letter O
X, X A hexadecimal integer, x is a lowercase representation, and X is an uppercase representation

The format control is placed after the placeholder index or placeholder name, separated by a colon, for example {1:D} indicates that the placeholder format parameter with index 1 is a decimal integer. In Python
The example running in the shell is as follows:

 >>> name = ' Mary ' >>> age = 18>>> Money = 1234.5678> >> "{0} Christina is {1:d} years old. ". Format (name, age) ① ' Mary Christina is 18 years old. ' >>> ' {1} christina is {0:5d} years old. ". Format (age, name) ② ' Mary Christina is 18 years old. ' >>> ' {0} revenue today is {1:f} yuan. ". Format (name, money) ③ ' Mary is earning $1234.567800 today. ' >>> ' {0} revenue today is {1:.2f} yuan. ". Format (name, money) ④ ' Mary is earning $1234.57 today. ' >>> ' {0} revenue today is {1:10.2f} yuan. ". Format (name, money) ⑤ ' Mary is earning $1234.57 today. ' >>> ' {0} revenue today is {1:g} yuan. ". Format (name, money) ' Mary's income today is 1234.57 yuan. ' >>> ' {0} revenue today is {1:g} yuan. ". Format (name, money) ' Mary's income today is 1234.57 yuan. ' >>> ' {0} revenue today is {1:e} yuan. ". Format (name, money) ' Mary's income today is 1.234568e+03 yuan. ' >>> ' {0} revenue today is {1:e} yuan. ". Format (name, money) ' Mary's income today is 1.234568E+03 yuan. The octal representation of the ' >>> ' decimal number {0:d} is {0:o} and the hexadecimal representation is {0:x} '. Format (28) ' Octal representation of decimal number 28 is 34, hexadecimal is 1c '  

The above code in line ① {1:D} is a formatted decimal integer, the code ② line {0:5d} is a string specifying the output length of 5, not enough space. The code in line ③ {1:D} is a formatted decimal floating-point number, visible from the result of the output, the fractional part is too long, if you want to control the decimal portion you can use the {1:.2f} placeholder of the code ④ line, which represents the reserved decimal two bits (rounded). If you want to set the length you can use the {1:10.2f} placeholder for line ⑤ of code, where 10 represents the total length, including the decimal point and fractional part, and not enough space to fill the position.

String Lookup

Finding substrings in a given string is a more common operation. The Find and RFind methods are provided in the String Class (str) to find the substring, the return value is where the lookup substring is located, and no return-1 is found. Only the Find and RFind methods are specified below.

    • Str.find (sub[, start[,
      end]]). Finds a substring between the index start and End Sub, if it finds an index that returns the leftmost position, if no return-1 is found. Start is the start index and end is the end index, both of which can be omitted if start omits the description to find the beginning of the string header, or if end omits to find the end of the string, if all is omitted to find all the strings.

    • Str.rfind (sub[, start[,
      end]]). Similar to the Find method, the difference is if you find the index that returns the most right-hand position. If only one virgin string is found within the scope of the lookup, here the Find and RFind methods return the same value.

Tip in a python document [] means that you can omit parts of the Find and RFind method parameters [, start[,
end]] means that both start and end can be omitted.

Run the sample code in the Python shell as follows:

>>> source_str = "There is a string accessing example.">>> len(source_str)             ①36>>> source_str[16]              ②‘g‘>>> source_str.find(‘r‘)            3>>> source_str.rfind(‘r‘)13>>> source_str.find(‘ing‘)14>>> source_str.rfind(‘ing‘)24>>> source_str.find(‘e‘, 15)21>>> source_str.rfind(‘e‘, 15)34>>> source_str.find(‘ing‘, 5)14>>> source_str.rfind(‘ing‘, 5)24>>> source_str.find(‘ing‘, 18, 28)24>>> source_str.rfind(‘ingg‘, 5)-1

The preceding code, ① len (SOURCE_STR), returns the length of the string, noting that Len is a function, not a method of a string, whose arguments are strings. Code ② Line SOURCE_STR[16] accesses the character of index 16 in the string.

The string lookup method above is similar, here the emphasis explains source_str.find (' ing ',
5) and source_str.rfind (' ing ',
5) An expression. The ING string appears two times from figure 6-1, and the indexes are 14 and 24, respectively. Source_str.find (' ing ',
5) returns the leftmost index 14, the return value is 14;source_str.rfind (' ing ', 5) returns the right-most index 24.

Tips
What is the difference between a function and a method? A method is a function defined in a class that needs to be called through a class or object when called outside the class, such as the Code source_str.find (' R ') above, which is the Find method that invokes the string object Source_str, which is defined in the Str class. The usual function is not defined in the class, also known as the top-level function, they do not belong to any class, the call directly using the function, such as Len (SOURCE_STR) in the above code, is called the Len function, but its parameters are the string object Source_str.

Strings and numbers convert to each other

In the actual programming process, strings and numbers are often used to convert to each other. The following describes the conversion of strings to numbers from two different aspects.

    1. Convert strings to Numbers

String conversions to numbers can be implemented using int () and float (), which in 6.2.2 describes conversions between numeric types, in fact both functions can also receive string arguments, and if the string can be successfully converted to a number, the number is returned, otherwise an exception is thrown.

Run the sample code in the Python shell as follows:

>>> int(‘9‘)9>>> int(‘9.6‘)Traceback (most recent call last):  File "<pyshell#2>", line 1, in <module>    int(‘9.6‘)ValueError: invalid literal for int() with base 10: ‘9.6‘>>> float(‘9.6‘)9.6>>> int(‘AB‘)Traceback (most recent call last):  File "<pyshell#4>", line 1, in <module>    int(‘AB‘)ValueError: invalid literal for int() with base 10: ‘AB‘>>>

By default, the Int () function converts the string argument to a decimal number, so int (' AB ') fails. the int () function can also specify cardinality (binary), in Python
The example running in the shell is as follows:

>>> int(‘AB‘, 16)171
    1. Convert numbers to Strings

There are many ways to convert a string to a number, and the string formatting described in section 6.3, 2, enables you to convert a number to a string. In addition, the string in Python provides the STR () function.

You can use the STR () function to convert any type of number to a string. In Python
Run the sample code in the shell as follows:

>>> str(3.24)‘3.24‘>>> str(True)‘True‘>>> str([])‘[]‘>>> str([1,2,3])‘[1, 2, 3]‘>>> str(34)‘34‘

From the above code can be the str () function is very powerful, what type can be converted. However, the disadvantage is that it cannot be formatted if the format string requires the use of the Format function. In Python
Run the sample code in the shell as follows:

>>> ‘{0:.2f}‘.format(3.24)‘3.24‘>>> ‘{:.1f}‘.format(3.24)‘3.2‘>>> ‘{:10.1f}‘.format(3.24)‘       3.2‘

Tip When formatting a string, if there is only one argument, the placeholder index can be omitted.

Summary of this chapter

This chapter focuses on data types in Python, where the reader needs to focus on numeric types and string types, familiarity with the conversion of numeric types to each other, and conversions between numeric types and strings.

Companion video

Http://edu.51cto.com/topic/1507.html

Supporting source code

Http://www.zhijieketang.com/group/8

Ebook

Https://yuedu.baidu.com/ebook/5823871e59fafab069dc5022aaea998fcc2240fc

Author Micro-blog: @tony_ dongsheng br/> Email:[email protected]

Python Reader service QQ Group: 628808216

Python from small white to Daniel 6th data types

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.