Python3基础进阶(一)

时间:2023-02-13 19:59:27

Chapter 2. Py Ingredients: Numbers, Strings, and Variables

Variables, Names, and Objects

In Python, everything-booleans, integers, floats, strings, even large data structures, functions, and programs—is implemented as an object. An object is like a clear plastic box that contains a piece of data.

The type also determines if the data value contained by the box can be changed (mutable) or is constant (immutable). Think of an immutable object as a closed box with a clear window: you can see the value but you can’t change it. By the same analogy, a mutable object is like an open box: not only can you see the value inside, you can also change it; however, you can’t change its type.

Variables are just names. Assignment does not copy a value; it just attaches a name to the object that contains the data. The name is a reference to a thing rather than the thing itself. Think of a name as a sticky note.

a = 7

Python3基础进阶(一)

If you want to know the type of anything (a variable or a literal value), use type( thing ).

>>> type(99.9)
<class 'float'>
>>> type('type')
<class 'str'>

In Python, “class” and “type” mean pretty much the same thing.

Variable names can only contain these characters: Lowercase letters (a through z); Uppercase letters (A through Z); Digits (0 through 9); Underscore (_).
Names cannot begin with a digit. Also, Python treats names that begin with an underscore in special ways.

Python’s reserved words:These words, and some punctuation, are used to define Python’s syntax.
Python3基础进阶(一)

Numbers

Python3基础进阶(一)

Integers


You can use a plain zero (0). But don’t put it in front of other digits:

>>> 05
SyntaxError: invalid token

Division is a little more interesting, because it comes in two flavors:

/ carries out floating-point (decimal) division

// performs integer (truncating:截断) division

You can combine the arithmetic operators with assignment by putting the operator before the =.

>>> a = 99
>>> a -= 9
>>> a
90

Here’s how to get both the (truncated) quotient and remainder at once:

>>> divmod(9, 5)
(1, 4)

A function named divmod is given the integers 9 and 5 and returns a two-item result called a tuple.

Precedence

Bases

In Python, you can express literal integers in three bases besides decimal:
0b or 0B for binary (base 2)
0o or 0O for octal (base 8)
0x or 0X for hex(Hexadecimal) (base 16).

Why use a different base from 10? It’s useful in bit-level operations.

Type Conversions

How Big Is an int?

In Python 3, long is long gone, and an int can be any size—even greater than 64 bits. In many languages, trying this would cause something called integer overflow, where the number would need more space than the computer allowed for it, causing various bad effects. Python handles humungous integers with no problem.

Floats

Strings

Logical (and creative!) thinking is often more important than math skills.

Because of its support for the Unicode standard, Python 3 can contain characters from any written language in the world, plus a lot of symbols. Its handling of that standard was a big reason for its split from Python 2.

Strings are our first example of a Python sequence. In this case, they’re a sequence of characters.

Strings in Python are immutable. You can’t change a string inplace, but you can copy parts of strings to another string to get the same effect.

Create with Quotes

You make a Python string by enclosing characters in either single quotes or double quotes. Why have two kinds of quote characters? The main purpose is so that you can create strings containing quote characters.You can also use three single quotes (”’) or three double quotes (“”“). Triple quotes aren’t very useful for short strings. Their most common use is to create multiline strings.

If you have multiple lines within triple quotes, the line ending characters will be preserved in the string. There’s a difference between the output of print() and the automatic echoing done by the interactive interpreter:

>>> country = '''China England USA '''
>>> country
'China\nEngland\nUSA\n'
>>> print(country)
China
England
USA

Convert Data Types by Using str()

Escape with \

By preceding a character with a backslash, you give it a special meaning. The most common escape sequence is \n, which means to begin a new line. With this you can create multiline strings from a one-line string.

>>> country = 'China\nEngland\nUSA '
>>> print(country)
China
England
USA

Combine with +

You can combine literal strings or string variables in Python by using the + operator, as demonstrated here:

>>> 'China' + 'USA'
'ChinaUSA'

Python does not add spaces for you when concatenating strings, so in the preceding example, we needed to include spaces explicitly. It does add a space between each argument to a print() statement, and a newline at the end:

>>> a = 'China'
>>> b = 'USA'
>>> c = 'England'
>>> print(a,b,c)
China USA England

Duplicate with *

Extract a Character with []

To get a single character from a string, specify its offset inside square brackets after the string’s name. The first (leftmost) offset is 0, the next is 1, and so on. The last (rightmost) offset can be specified with –1 so you don’t have to count.

Because strings are immutable, you can’t insert a character directly into one or change the character at a specific index. Instead you need to use some combination of string functions such as replace() or a slice.

>>> a = 'China'
>>> a[0] = 'U'
Traceback (most recent call last):
  File "<pyshell#36>", line 1, in <module>
    a[0] = 'U'
TypeError: 'str' object does not support item assignment

>>> a.replace('C', 'U')
'Uhina'

>>> 'U' + a[1:]
'Uhina'

Slice with [ start : end : step ]

You can extract a substring (a part of a string) from a string by using a slice. You define a slice by using square brackets, a start offset, an end offset, and an optional step size. Some of these can be omitted. The slice will include characters from offset start to one before end.

If you don’t specify start, the slice uses 0 (the beginning). If you don’t specify end, it uses the end of the string.

>>> letters = 'abcdefg'
>>> letters[:]
'abcdefg'

Get Length with len()

The len() function counts characters in a string:

>>> letters = 'abcdefg'
>>> len(letters)
7

Split with split()

Some functions are specific to strings. To use a string function, type the name of the string, a dot, the name of the function, and any arguments that the function needs:

string . function ( arguments )

You can use the built-in string split() function to break a string into a list of smaller strings based on some separator.

>>> letters = 'abc,def,ghi'
>>> letters.split(',')
['abc', 'def', 'ghi']

In the preceding example, the string was called letters and the string function was called split(), with the single separator argument ‘,’. If you don’t specify a separator, split() uses any sequence of white space characters—newlines, spaces, and tabs.

>>> letters = 'a b c d,ef gh,i'
>>> letters.split()
['a', 'b', 'c', 'd,ef', 'gh,i']

Combine with join()

The join() function is the opposite of split(): it collapses a list of strings into a single string.

>>> crypto_list = ['a', 'b', 'c']
>>> crypto_string = '-'.join(crypto_list)
>>> crypto_string
'a-b-c'

Playing with Strings

Python has a large set of string functions. Let’s explore how the most common of them work.

>>> poem = '''All that doth flow we cannot liquid name
Or else would fire and water be the same;
But that is liquid which is moist and wet
Fire that property can never get.
Then 'tis not cold that doth the fire put out
But 'tis the wet that makes it die, no doubt.'''

Does it start with the letters All?

>>> poem.startswith('All')
True

Does it end with That’s all, folks!?

>>> poem.endswith('That\'s all, folks!')
False

let’s find the offset of the first occurrence of the word the in the poem:

>>> poem.find('the')
73

And the offset of the last the:

>>> poem.rfind('the')
214

How many times does the three-letter sequence the occur?

>>> poem.count('the')
3

Are all of the characters in the poem either letters or numbers?

>>> poem.isalnum()
False

Nope, there were some punctuation characters.

Case and Alignment

In this section, we’ll look at some more uses of the built-in string functions.

Our test string is the following:

>>> setup = '...a ..duck goes into a bar...'
>>> setup.strip('.')
'a ..duck goes into a bar'    # Remove . sequences from both ends

Because strings are immutable, none of these examples actually changes the setup string. Each example just takes the value of setup, does something to it, and returns the result as a new string.

>>> setup = 'a duck goes into a bar...'
>>> setup.capitalize()
'A duck goes into a bar...'
>>> setup.title()
'A Duck Goes Into A Bar...'
>>> setup.upper()
'A DUCK GOES INTO A BAR...'
>>> setup.lower()
'a duck goes into a bar...'

>>> setup = 'a duck goes into a Bar...'
>>> setup.swapcase()
'A DUCK GOES INTO A bAR...'

Now, we’ll work with some layout alignment functions.

>>> setup = 'a duck goes into a Bar...'
>>> setup.center(30)
' a duck goes into a Bar... '

>>> setup = 'a duck goes into a Bar...'
>>> setup.ljust(30)
'a duck goes into a Bar... '
>>> setup.rjust(30)
' a duck goes into a Bar...'

Substitute with replace()

You use replace() for simple substring substitution. You give it the old substring, the new one, and how many instances of the old substring to replace. If you omit this final count argument, it replaces all instances.

>>> setup = 'a b c a b c a'
>>> setup.replace('a', 'd', 2)
'd b c d b c a'

Sometimes, you want to ensure that the substring is a whole word, or the beginning of a word, and so on. In those cases, you need regular expressions.