Python from small white to Daniel 6th data types

Source: Internet
Author: User
Tags control characters string to number


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:

>>> 28
28
>>> 0b11100
28
>>> 0O34
28
>>> 0o34
28
>>> 0x1C
28
>>> 0X1C
28
Floating point type
Floating-point types are mainly used to store decimal values. Python's floating-point type is float. Python only supports double-precision floating-point types, and is natively related.

Floating point types can be expressed in decimal or scientific notation. In scientific notation, an uppercase or lowercase e is used to represent the exponent of 10, such as e2 is used to represent 102.

Run the example in the Python Shell as follows:

>>> 1.0
1.0
>>> 0.0
0.0
>>> 3.36e2
336.0
>>> 1.56e-2
0.0156
Among them, 3.36e2 represents 3.36 × 102, and 1.56e-2 represents 1.56 × 10-2.

Plural type
Complex numbers are very important concepts in mathematics, and they are often used in theoretical physics and electrical engineering practice. But many computer languages do not support complex numbers, and Python supports complex numbers, which makes Python well used for scientific calculations.

Complex types in Python are complex. For example, 1 + 2j represents a complex number with real part 1 and imaginary part 2. In Python
The running example in the shell is as follows:

>>> 1 + 2j
(1 + 2j)
>>> (1 + 2j) + (1 + 2j)
(2 + 4j)
The above code adds two complex numbers (1 + 2j).

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

note
Any type of data can be converted to boolean values using the bool () function. Those values that are considered "not" and "empty" are converted to False, and vice versa. Values such as None (empty object), False, 0, 0.0, 0j (plural), '' (empty string), [] (empty list), () (empty tuple), and {} (empty dictionary) Converted to False, otherwise True.

Examples are:

>>> bool (0)
False
>>> bool (2)
True
>>> bool (1)
True
>>> bool (‘‘)
False
>>> bool (‘‘)
True
>>> bool ([])
False
>>> bool ((})
False
The bool (2) and bool (1) expressions in the above code are True, which means that both 2 and 1 can be converted to True, and only 0 in integers is converted to False, as are other types.

Number type conversion
After learning the previous data types, everyone will think about a question, is it possible to convert between data types? Python passes functions to convert between different data types. Such as: conversion between digital types and conversion between integers and strings. This section first discusses the conversion between numeric types.

In addition to complex numbers, the other three types of integers, floating point, and Boolean can be converted to each other. The conversion is divided into implicit type conversion and explicit type conversion.

Implicit type conversion
Mathematical calculations can be performed between multiple numeric types of data. Since the types of numbers involved in the calculations may be different, implicit type conversions occur at this time. Table 6-1 shows the rules for implicit type conversion during calculation.

Table 6-1 Implicit type conversion rules

Operand 1 type Operand 2 type Conversion type
Boolean integer integer
Boolean, integer, floating point, floating point
Boolean values can be implicitly converted to integer types, Boolean True to integer 1, and False to integer 0. In Python
The running example 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 the operation result of the above code expression, the type conversion rules shown in Table 6-1 are known, and details are not repeated here. In addition, line ① of the above code uses the type () function,
The type () function can return the type of the incoming data. \ <class ‘float’ \> means that it is a floating point type.

Explicit type conversion
In cases where implicit conversions cannot be performed, you can use conversion functions to perform explicit conversions. In addition to complex numbers, the three numeric types integer, floating point, and Boolean have their own conversion functions, which are int (), float (), and bool () functions. The bool () function was introduced in Section 6.1.4. I won't repeat them here.

The int () function can convert Boolean, floating point, and string to integers. Boolean values True use the int () function to return 1, False use the int () function to return 0; floating-point numbers use the int () function to truncate the decimal part. The int () function for converting strings will be described in the next section.

The float () function can convert Boolean, integer, and string to floating point. The boolean value True uses the float () function to return 1.0, False uses the float () function to return 0.0; the integer value uses the float () function to add the decimal part (.0). The float () function for converting strings 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 series of character sequences consisting of characters, called "strings". Strings are in order, from left to right, and the index increases from 0. The string type in Python is str.

String representation
There are three ways to represent strings in Python:

Ordinary string. Strings enclosed in single quotes (') or double quotes (").

Raw string
string). Add r in front of ordinary strings, special characters in strings do not need to be escaped, and they are presented according to the original appearance of the string.

Long string. The string contains typesetting characters such as newline indentation. It can be wrapped in triple single quotes (‘‘ ‘) or triple double quotes (" ""). This is a long string.
Ordinary string
Many programmers are used to using single quotes (') to represent strings. The following examples represent Hello World strings:

‘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 encoded in Unicode, so strings can contain Asian characters such as Chinese. The strings in line ① and line ② of the code are strings expressed by Unicode encoding. In fact, they also represent Hello.
World string, you can output the string represented by Unicode encoding 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 them in ordinary strings, and you need to precede them with a backslash (\), which is called character escaping. Table 6-2 shows several commonly used escape characters.

Table 6? 2 Escape characters

Character representation Unicode encoding
\ t \ u0009 Horizontal tab
\ n \ u000a Newline
\ r \ u000d Enter
\ "\ u0022 double quotes
\ ‘\ U0027 single quote
\\ \ u005c backslash
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 quotes (') and double quotes (") in the string, you can also avoid escape characters. Use double quotes to wrap strings in strings containing single quotes. See line ① of the code; for characters containing double quotes Use single quotes to wrap the string in the string, see line ② of the code. In addition, you can use Unicode to replace special characters that need to be escaped. Line ④ of code is equivalent to code ③.

Raw string
Add the letter r in front of the ordinary string to indicate that the string is the original string. The original string is used directly according to the literal meaning of the string, without escape characters. In Python
The sample code running in the shell is as follows:

>>> s = ‘Hello \ tWorld’ ①
>>> print (s)
Hello World
>>> s = r‘Hello \ tWorld ’②
>>> print (s)
Hello \ tWorld
Code ① is an ordinary string, and code ② is an original string. The only difference is that the letter r is prepended to the string. As you can see from the output, \ t in the original string is not used as a tab.

Long string
The string contains typesetting characters such as newline indentation, so you can use long strings. In Python
The sample code running in the shell is as follows:

>>> s = ‘‘ ‘Hello
 World ‘‘ ‘
>>> print (s)
Hello
 World
>>> s = "" "Hello \ t ①
        World "" "
>>> print (s)
 Hello
        World
If long strings contain special characters, they also need to be escaped, see line ① of the code.

String formatting
In the actual programming process, it is often encountered to stitch other types of variables and strings together and format the output. For example, the calculated amount needs to retain four decimal places, the numbers need to be right-aligned, etc. These all need to be formatted.

You can use the string's format () method and placeholders when formatting strings. In Python
The running example in the shell is as follows:

>>> name = ‘Mary’
>>> age = 18
>>> s = ‘she is {0} years old. ‘.Format (age) ①
>>> print (s)
She is 18 years old.
>>> s = ‘{0} Fang ’s age is {1}. ‘.Format (name, age) ②
>>> print (s)
Mary is 18 years old.
>>> s = ‘{1} Fang is {0} years old. ‘.Format (age, name) ③
>>> print (s)
Mary is 18 years old.
>>> s = ‘{n} Fang ’s age is {a}. ‘.Format (n = name, a = age) ④
>>> print (s)
Mary is 18 years old.
There can be placeholders (contents represented by {}) in the string. When used with the format () method, the parameters in the format () method will replace the placeholder content. Placeholders can be represented by parameter indexes, see lines ①, ②, and ③ of the code. You can also use parameter names to represent placeholders. See line ④ of the code. Both n and a are parameter names.

There can also be formatting controls in the placeholders for more precise control over the format of the string. Different data types require different control characters when formatting. These formatting control characters are shown in Table 6-3.

Table 6-3 String formatting control characters

Control symbol
s string formatting
d decimal integer
f, F decimal floating point number
g, G decimal integer or floating point number
e 、 E Scientific calculation method means floating point number
o Octal integer, the symbol is the small English letter o
x, X hexadecimal integer, x is lowercase, X is uppercase
The format control character is located after the placeholder index or the placeholder name, separated by colons. For example, {1: d} indicates that the placeholder index with the format parameter is a decimal integer. In Python
The running example in the shell is as follows:

>>> name = ‘Mary’
>>> age = 18
>>> money = 1234.5678
>>> "{0} Fangling is {1: d} years old.". Format (name, age) ①
‘Mary Fang is 18 years old. ‘
>>> "{1} Fang's age is {0: 5d}".
‘Mary Fang is 18 years old. ‘
>>> "Today's {0} income is {1: f} yuan.". Format (name, money) ③
‘Mary ’s income today is 1234.567800 yuan. ‘
>>> "The income of {0} today is {1: .2f} yuan.". Format (name, money) ④
‘Mary ’s income today is 1234.57 yuan. ‘
>>> "The income of {0} today is {1: 10.2f} yuan.". Format (name, money) ⑤
‘Mary ’s income today is 1,234.57 yuan. ‘
>>> "{0} today's income is {1: g} yuan.". Format (name, money)
‘Mary ’s income today is 1234.57 yuan. ‘
>>> "{0} today's income is {1: G} yuan.". Format (name, money)
‘Mary ’s income today is 1234.57 yuan. ‘
>>> "{0} today's income is {1: e} yuan.". Format (name, money)
‘Mary ’s income today is 1.234568e + 03 yuan. ‘
>>> "{0} today's income is {1: E} yuan.". Format (name, money)
‘Mary ’s income today is 1.234568E + 03 yuan. ‘
>>> ‘Octal representation of the decimal number {0: d} is {0: o} and hexadecimal representation is {0: x}’. Format (28)
‘Octal representation of the decimal number 28 is 34, and hexadecimal representation is 1c’
{1: d} in the first line of the above code is a formatted decimal integer, and {0: 5d} in the second line of the code is a character string with a specified output length of 5. {1: d} in the third line of the code is a formatted decimal floating-point number. It can be seen from the output that the decimal part is too long. If you want to control the decimal part, you can use the {1: .2f} placeholder in the fourth line , Where two decimal places are reserved (rounded). If you want to set the length, you can use the {1: 10.2f} placeholder on line ⑤ of the code, where 10 represents the total length, including the decimal point and the decimal part, and it is not enough to fill in spaces.

String lookup
Finding substrings in a given string is a common operation. The string class (str) provides find and rfind methods for finding substrings. The return value is where the substring is located. If not found, -1 is returned. Only the find and rfind methods are specifically explained below.

str.find (sub [, start [,
end]]). Find the substring sub between the index start and end, and return the leftmost index if found, or -1 if not found. Start is the start index and end is the end index. Both parameters can be omitted. If start is omitted, the search starts from the beginning of the string; if end is omitted, the search ends at the end of the string.

str.rfind (sub [, start [,
end]]). Similar to the find method, the difference is that if an index is returned that returns the rightmost position. If only one substring is found in the search range, then the find and rfind methods return the same value.
Tip In the Python documentation, [] means that you can omit the part, and 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‘)
twenty four
>>> source_str.find (‘e’, 15)
twenty one
>>> source_str.rfind (‘e’, 15)
34
>>> source_str.find (‘ing‘, 5)
14
>>> source_str.rfind (‘ing‘, 5)
twenty four
>>> source_str.find (‘ing‘, 18, 28)
twenty four
>>> source_str.rfind (‘ingg’, 5)
-1
The first line of the above code len (source_str) returns the length of the string. Note that len is a function, not a method of strings, and its parameter is a string. The second line of source_str [16] accesses the character at index 16 in the string.

The above string search method is similar. Here we explain the source_str.find (‘ing’,
5) and source_str.rfind (‘ing‘,
5) Expression. It can be seen from Figure 6-1 that the ing string appears twice, and the indexes are 14 and 24, respectively. source_str.find (‘ing‘,
5) Returns the leftmost index 14 with a return value of 14; source_str.rfind (‘ing’, 5) returns the rightmost index 24.

prompt
The difference between a function and a method? A method is a function defined in a class, which needs to be called by a class or an object when called outside the class. For example, the above source_str.find ('r') method calls the find method of the string object source_str. The find method is in the str class. Defined. The usual functions are not defined in the class, they are also called top-level functions. They do not belong to any class. You can use the function directly when you call it. The parameter is the string object source_str.

Convert strings to numbers
In the actual programming process, string and number conversion is often used. The following describes the conversion of strings and numbers from two different aspects.

String to Number
Strings can be converted to numbers using int () and float (). These two functions are described in Section 6.2.2 to convert between numeric types. In fact, these two functions can also accept string parameters. 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 string parameters as decimal numbers, so int (‘AB’) fails. The int () function can also specify the radix (base) in Python
The running example in the shell is as follows:

>>> int (‘AB’, 16)
171
Number to string
There are many ways to convert strings to numbers. The string formatting described in Section 6.3.2 can convert numbers to strings. In addition, strings in Python provide the str () function.

You can use the str () function to convert any type of number to a string. In Python
The sample code running in the shell is 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, the str () function is very powerful, and any type can be converted. However, the disadvantage is that it cannot be formatted. If you need to format the string, you need to use the format function. In Python
The sample code running in the shell is 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 parameter, the placeholder index can be omitted.

chapter summary
This chapter mainly introduces the data types in Python. The reader needs to focus on mastering number types and string types, familiar with the conversion between number types, and the conversion between number types and strings.

Supporting 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 Weibo: @tony_ 关 东升 Email: [email protected]
Python Reader Service QQ Group: 628808216

"Python from Little White to Big Cow" Chapter 6 Data Types

Related Article

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.