程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Quick start to python programming first six chapters theory part reading notes

編輯:Python

Catalog

  • Common mistakes
  • Chapter one python Basics
    • 1.1 String linking and copying
    • 1.2 Variable name
    • 1.3 notes
    • 1.4 Three functions
    • 1.5 Text and number are equal
    • 1.6 exercises
  • Chapter two control flow
    • 2.1 Boolean value
    • 2.2 Comparison operator
    • 2.3 Boolean operator
    • 2.4 Mix Boolean and compare operators
    • 2.5 The elements that control the flow
      • 2.5.1 Conditions
      • 2.5.2 Code block
    • 2.6 Control flow statement
      • if sentence
      • else sentence
      • elif sentence
      • while Loop statement
      • break sentence
      • continue sentence
        • Release the dead cycle
      • for Circulation and range() function
      • equivalent while loop
      • range() The beginning of 、 Stop and step parameters
    • 2.7 The import module
      • from import sentence
    • 2.8 use sys.exit() End the program ahead of time
  • The third chapter function
    • 3.1 def Statements and parameters
    • 3.2 Return values and return sentence
    • 3.3 None value
    • 3.4 Keyword parameters and print()
    • 3.5 Local and global scope
      • 3.5.1 Local variables cannot be used in global scope
      • 3.5.2 Local scopes cannot use variables in other local scopes
      • 3.5.3 Global variables can be read in local scope
      • 3.5.4 Local and global variables with the same name
    • 3.6 global sentence
    • 3.7 exception handling
      • Function as “ Black box ”
    • 3.8 A little program : Guess the number
  • Chapter four
    • 4.1 List data type
      • 4.1.1 Get a single value in the list with a subscript
      • 4.1.2 Negative subscript
      • 4.1.3 Use slice to get sublist
      • 4.1.4 use len() Get the length of the list
      • 4.1.5 Use the subscript to change the value in the list
      • 4.1.6 List connection and list replication
      • 4.1.7 use del Statement to delete a value from the list
    • 4.2 Use list
      • 4.2.1 The list is used for looping
    • 4.2.2 in and not in The operator
      • 4.2.3 Multiple assignment techniques
    • 4.3 Enhanced assignment operation
    • 4.4 Method
      • 4.4.1 use index() Method to find a value in the list
    • 4.4.2 use append() and insert() Method to add a value... To the list
      • 4.4.3 use remove() Method to delete a value from the list
      • 4.4.4 use sort() Method to sort the values in the list
    • **4.5Python Exceptions to the indentation rule in **
    • 4.6 List like type : Strings and tuples
      • 4.6.1 Variable and immutable data types
      • 4.6.2 Tuple data type
      • 4.6.3 use list() and tuple() Function to convert type
    • 4.7 quote
      • 4.7.1 Pass on references
      • 4.7.2 copy Modular copy() and deepcopy() function
    • 4.8 Summary
      • end keyword
    • 4.9 Project practice
  • The fifth chapter Dictionaries and structured data
    • 5.1 Dictionary data type
      • 5.1.1 Dictionaries and lists
      • 5.1.2 keys()、values() and items() Method
      • 5.1.3 Check the dictionary for keys or values
      • 5.1.4 get() Method
      • 5.1.5 setdefault() Method
    • 5.2 Beautiful printing
    • 5.3 Use data structures to model the real world
      • 5.3.1 Tic tac toe chessboard
      • 5.3.2 Nested dictionaries and lists
  • Chapter six String manipulation
    • 6.1 Processing strings
      • 6.1.1 Literal of a string
      • 6.1.2 Double quotes
      • 6.1.3 Escape character
      • 6.1.4 Original string
      • 6.1.5 Multiline string with triple quotes
      • 6.1.6 Multiline comment
      • 6.1.7 String subscripts and slices
      • 6.1.8 A string of in and not in The operator
    • 6.2 Useful string methods
      • 6.2.1 String method upper()、lower()、isupper() and islower()
      • 6.2.2 isX String method
      • 6.2.3 String method startswith() and endswith()
      • 6.2.4 String method join() and split()
      • 6.2.5 use rjust()、ljust() and center() Method to align text
      • 6.2.6 use strip()、rstrip() and lstrip() Delete white space characters
      • 6.2.7 use pyperclip Module copy and paste string
    • 6.3 Project password safe deposit box
    • 6.4 Change the clipboard contents into an unordered list
    • Programming operation

Common mistakes

1.SyntaxError: EOL while scanning string literal

( forget The single quotation mark at the end of the string )

2.TypeError: ‘int’ object is not iterable

reason : Can't be used directly int To iterate , And you have to add range.

for index in range(len(numbers)): correct

for i in len(index): error

3.KeyError: ‘color’

Try to access a key that does not exist in the dictionary , Will lead to KeyError Error message . It's a lot like a list “ Transboundary ” IndexError Error message .

Chapter one python Basics

1.1 String linking and copying

The code must explicitly convert an integer to a string , because Python No

Can automatically complete the conversion .

When used with two integer or floating-point values , The operator represents multiplication . but The operator is used for a string Value and an integer value , It became “ String copy ” The operator . Enter a word in an interactive environment Multiply a number by a string , Look at the effect .

>>> ‘Alice’ * 5

‘AliceAliceAliceAliceAlice’

* The operator can only be used for two numbers ( As multiplication ), Or a string and an integer ( As character String copy operator )

print Only the output str type , To carry out format conversion

1.2 Variable name

1. It can only be one word .

2. Can only contain letters 、 Numbers and underscores .

3. Cannot start with a number .

The variable name uses the hump form

1.3 notes

# All text after the flag is a comment .

1.4 Three functions

input Output str

len The output is an integer

int Yes str Type error , such as **int(’7.7‘)** error , **int(7.7)** correct

round() Method returns a floating-point number x Round the value of .

1.5 Text and number are equal

Although string values of numbers are considered to be completely different from integer and floating-point values , But integer values can be equal to floating-point values .

Because strings are text , Both integer values and floating-point values are numbers .

1.6 exercises

The difference between expression and statement

An expression produces a value , It can be placed anywhere you need a value

A statement can be understood as an action . Loop statements and if A sentence is a typical sentence . A program is made up of a series of statements .

expression

Is composed of operators and operands , A single operand ( Constant / Variable ) It can also be called an expression , This is the simplest expression .

Chapter two control flow

2.1 Boolean value

Boolean value True and False

Unlike string , No quotation marks around , They are always in capital letters T or F start , Lower case after

2.2 Comparison operator

==

be equal to

!=

It's not equal to

<

Less than

>

Greater than

<=

Less than or equal to

>=

Greater than or equal to

== and != Operators can actually be used for values of all data types

Please note that , Integer or floating-point values will never be equal to strings . expression 42 == '42’ Evaluated as False Because ,Python Consider integer 42 And string ’42’ Different .

On the other hand ,<、>、<= and >= Operators are only used for integer and floating-point values

2.3 Boolean operator

3 Boolean operators (and、or and not) Used to compare Boolean values .

not The operator asks for Value is the opposite Boolean value

not True=false

2.4 Mix Boolean and compare operators

The computer will first evaluate the expression on the left , Then evaluate the expression on the right . After knowing two Boolean values , It evaluates the entire expression to a Boolean value .

Like arithmetic operators , Boolean operators also have an order of operations . Evaluate all arithmetic and comparison operators after ,Python Evaluate first not The operator , And then there was and The operator , And then there was or The operator .

2.5 The elements that control the flow

2.5.1 Conditions

The condition always evaluates to a Boolean ,True or False. control The flow statement is based on the condition that True still False, To decide what to do . Almost all control flow statements use conditions .

2.5.2 Code block

Some lines of code can be used as a group , Put it in “ Code block ” in . Can be based on the line of code Indent , know The beginning and end of the code block . The code block has 3 Bar rule .

1. When indent increases , Code block start .

2. Code blocks can contain other code blocks .

3. Indent reduced to zero , Or reduce it to the indent surrounding the code block , The code block is over .

2.6 Control flow statement

if sentence

The most common control flow statements are if sentence .if The clause of a statement ( That is to follow if Statement block of statement ), The condition of the statement will be True When the . If the condition is False, Clause will skip . In English ,if The sentence may read :“ If the condition is true , Execute the code in the clause .” stay Python

in ,if The statement contains the following parts :

 if keyword ;

 Conditions ( That is to say, the evaluation is True or False The expression of );

 The colon ;

 Start on the next line , Indented code block ( be called if Clause ).

if name == 'Alice':
print('Hi, Alice.')

else sentence

if Clauses can sometimes be followed by else sentence . Only if The condition of the statement is False when ,else Clause will execute . In English ,else The sentence may read :“ If the condition is true , Carry out this paragraph Code . otherwise , Execute that code ”.else The statement does not contain a condition , In the code ,else Statement contains Including the following parts :

 else keyword ;

 The colon ;

 Start on the next line , Indented code block ( be called else Clause ).

if name == 'Alice':
print('Hi, Alice.')
else:
print('Hello, stranger.')

elif sentence

Although only if or else Clause will be executed , But sometimes you may want to ,“ many ” Possible clauses

One of them is executed .elif The sentence is “ Otherwise, if ”, Always follow if Or another elif Statement behind . it

Provides another condition , Only if the preceding condition is False Check this condition only when . In the code ,elif sentence

Always include the following :

 elif keyword ;

 Conditions ( That is to say, the evaluation is True or False The expression of );

 The colon ;

 Start on the next line , Indented code block ( be called elif Clause ).

if name == 'Alice':
print('Hi, Alice.')
elif age < 12:
print('You are not Alice, kiddo.')

notes : At most one clause will be executed , about elif sentence , Order is very important .

print("input your name")
name=input()
print('input your age')
age=int(input())
if name=='wpc':
print('hi wpc')
elif age<20:
print('you are not wpc,boy')
elif age >100:
print('you are not wpc,grandfather')
elif age >3000:
print('he is not dead')

while Loop statement

utilize while sentence , You can let a block of code execute over and over again . as long as while The condition of the statement is True,while The code in the clause will execute . In the code ,while Statements always contain the following

part :

 keyword ;

 Conditions ( Evaluated as True or False The expression of );

 The colon ;

 Start with a new line , Indented code block ( be called while Clause ).

spam = 0
while spam < 5:
print('Hello, world.')
spam = spam + 1

break sentence

If execution encounters break sentence , Will quit immediately while Loop clause . In the code ,break The statement contains only break keyword .

while True:
print('Please type your name.')
name = input()
if name == 'your name':
break
print('Thank you!')

continue sentence

continue Statement is used inside a loop . If program execution encounters continue sentence , Will immediately jump back to the beginning of the cycle , Re evaluate the loop condition ( This is what happens when the execution reaches the end of the loop )

Release the dead cycle

If you run this program , It will always print on the screen Hello world! because while The condition of a statement is always True. stay IDLE In the interactive environment window , There are only two ways to stop the program : Press down Ctrl-C Or choose... From the menu ShellRestart Shell. If you want to stop the program immediately , Even if it is not trapped in an infinite loop ,Ctrl-C It's also very convenient

for Circulation and range() function

When used for conditions ,0、0.0 and ’ '( An empty string ) Is considered to be False, Other values are considered True.

In the code ,for The statement looks like for i in range(5): such , Always include the following :

 for keyword ;

 A variable name ;

 in keyword ;

 call range() Method , At most 3 Parameters ;

 The colon ;

 Start with the next line , Chunks of code that shrink back ( be called for Clause ).

print('My name is')
for i in range(5):
print('Jimmy Five Times (' + str(i) + ')')

range Left closed right away , from 0 Start

equivalent while loop

It can actually be used while Loop to do and for Cycle the same thing ,for The loop is just simpler .

range() The beginning of 、 Stop and step parameters

Some functions can be called with multiple arguments , Parameters are separated by commas ,range() Is one of them .

This allows you to pass on changes to range() The integer of , Realize various integer sequences , Ranging from 0 Start with a value other than .

for i in range(12, 16):
print(i)
12
13
14
15
# result

range() A function can also have a third argument . The first two parameters are the start value and the end value , The third parameter is “ step ”. The step size is the value that the loop variable increases after each iteration .

call range(0, 10, 2) Will be taken from 0 Count to 8, The interval is 2.

0
2
4
6
8

It can be used

Negative number as step parameter , Let the cycle count gradually decrease , Rather than increasing .

2.7 The import module

Before you start using functions in a module , Must use import Statement to import the module . In the code ,

import The statement contains the following parts :

 import keyword ;

 Module name ;

 Optional more module names , Separated by commas .

import random, sys, os, math

import random
for i in range(5):
print(random.randint(1, 10))

random.randint() The function call evaluates to the... Passed to it Between two integers A random integer of . because randint() Belong to random modular , You must precede the function name with random., tell python stay random Find this function in the module .

from import sentence

import Another form of statement includes from keyword , Followed by the module name ,import Key words and An asterisk , for example from random import *.

Use this form of import sentence , call random The function in the module does not need random. Prefix .

however , Using full names makes the code more readable , So it's best to use the common form import sentence .

2.8 use sys.exit() End the program ahead of time

The last control flow concept to introduce , How to terminate the program . When the program reaches the bottom of the instruction , It always ends . however , By calling sys.exit() function , You can let the program terminate or exit . Because this function is in sys Module , So you must import sys, To use it .

import sys
while True:
print('Type exit to exit.')
response = input()
if response == 'exit':
sys.exit()
print('You typed ' + response + '.')

The third chapter function

The purpose of the function : Eliminate duplicate , Put together code that executes many times

3.1 def Statements and parameters

The first line is def sentence , It defines a named hello() Function of .def The code block after the statement is the function body . This code is executed when the function is called , Not when the function is first defined .

def hello(name):
print('Hello ' + name)
hello('Alice')
hello('Bob')

3.2 Return values and return sentence

use def Statement when creating a function , It can be used return Statement specifies what value should be returned .return Statement package

Including the following parts :

 return keyword ;

 The value or expression that the function should return .

An expression is a combination of values and operators . Function calls can be used in expressions , Because it evaluates to its return value .

3.3 None value

stay Python One of the values is called None, It means no value .None yes NoneType Unique value of data type ( Other programming languages may call this value null、nil or undefined). It's like Boolean True and False equally ,None It must be capitalized N.

All function calls need to be evaluated to a return value , that print() Just go back to None.print() The return value of is None

3.4 Keyword parameters and print()

Most parameters are identified by their position in the function call . for example ,random.randint(1, 10) And random.randint(10, 1) Different . Function call random.randint(1, 10) Will return 1 To 10 A random integer between , Because the first parameter is the lower bound of the range , The second parameter is the upper bound of the range ( and

random.randint(10, 1) Can cause errors ).

however ,“ Key parameters ” It is identified by the keywords added in front of them when the function is called . The key Word parameters are usually used for optional arguments . for example ,print() Function has optional arguments end and sep, Specify in What is printed at the end of the parameter , And what to print between parameters to separate them

because print() The function automatically adds a newline character to the end of the incoming string . however , You can set end Key parameters , Turn it into another string . for example ,

If the program looks like this :

print(‘Hello’, end=’’)

print(‘World’)

Output

HelloWorld

If to print() Pass in multiple string values , The function will automatically separate it with a space People . Enter the following code in the interactive environment

print(‘cats’, ‘dogs’, ‘mice’)

cats dogs mice

Pass in sep Key parameters , Replace the default delimited string . In an interactive environment

Enter the following code :

print(‘cats’, ‘dogs’, ‘mice’, sep=’,’)

cats,dogs,mice

3.5 Local and global scope

Arguments and variables assigned in the called function , At the end of the function “ Local scope ”. Variables assigned outside all functions , Belong to “ Global scope ”. Variables in local scope , go by the name of “ local variable ”. Variables in global scope , go by the name of “ Global variables ”. A variable must be one of them , It cannot be both local and global .

Can be “ Scope ” As a container for variables . When the scope is destroyed , The values of all variables stored in the scope are discarded . There is only one global scope , It was created at the beginning of the program . If the program terminates , The global scope is destroyed , All its variables are discarded . otherwise , The next time you run the program , These variables will remember their last run values .

When a function is called , A local scope is created . All variables assigned in this function , Exists within this local scope . When this function returns , This local scope is destroyed , These variables are lost . Next time you call this function , Local variables do not remember the value they held when the function was last called . Scope is important , For the following reasons :

 Code in the global scope cannot use any local variables ;

 however , Local scopes can access global variables ;

 Code in the local scope of a function , Variables in other local scopes cannot be used .

 If in different scopes , You can name different variables with the same name .

Relying on global variables is a bad habit

3.5.1 Local variables cannot be used in global scope

def spam():
eggs = 31337
spam()
print(eggs)
# Report errors

eggs Variables only belong to spam() Call the created local scope . In the process

Line from spam After the return , The local scope is destroyed , No longer named eggs The variable of .

3.5.2 Local scopes cannot use variables in other local scopes

def spam():
eggs = 99
bacon()
print(eggs)
def bacon():
ham = 101
eggs = 0
spam()
# Output is 99

The point is , The local variables in one function are completely separated from those in other functions .

3.5.3 Global variables can be read in local scope

def spam():
print(eggs)
eggs = 42
spam()
print(eggs)
# Print out 42

Because in spam() Function , There is no argument named eggs, There is no code for eggs assignment , So when spam() Use in eggs when ,Python Think of it as a global variable eggs References to . This is what the previous program prints out when it runs 42 Why

3.5.4 Local and global variables with the same name

To make life simple , Avoid local variables having the same name as global variables or other local variables . But technically , stay Python It is perfectly legal to have local variables and global variables have the same name in .

def spam():
eggs = 'spam local'
print(eggs) # prints 'spam local'
def bacon():
eggs = 'bacon local'
print(eggs) # prints 'bacon local'
spam()
print(eggs) # prints 'bacon local'
eggs = 'global'
bacon()
print(eggs) # prints 'global'

bacon local
spam local
bacon local
global

The local domain is obeyed when the local domain conflicts with the local domain

3.6 global sentence

If you need to modify global variables within a function , Just use global sentence . If at the top of the function

Yes global eggs This code , It tells me Python,“ In this function ,eggs It refers to the global change

The amount , So don't create a local variable with this name .”

def spam():
global eggs
eggs = 'spam'
eggs = 'global'
spam()
print(eggs)
# Output spam

because eggs stay spam() The top of is declared as global , So when eggs To be an assignment ’spam’ when ,

The assignment takes place in the global scope spam On . No local spam Variable .

Yes 4 Rules , To distinguish whether a variable is in local scope or global scope :

1. If the variable is used in the global scope ( That is, outside of all functions ), It is always a global variable .

2. If in a function , There are... For this variable global sentence , It's a global variable .

3. otherwise , If the variable is used for an assignment statement in a function , It's a local variable .

4. however , If the variable is not used in the assignment statement , It's a global variable .

def spam():
print(eggs) # normal
# eggs = 'spam local'
eggs = 'global'
spam()
def spam():
print(eggs) # ERROR!
eggs = 'spam local'
eggs = 'global'
spam()
#Python notice spam() The function is for eggs Assignment statement for , Therefore, we believe that eggs Variables are local variables

3.7 exception handling

stay Python An error was encountered in the program , or “ abnormal ”, It means the whole program crashes .

You don't want this to happen in real-world programs . contrary , You want the program to detect errors , Deal with them ,

Then keep running .

def spam(divideBy):
return 42 / divideBy
print(spam(2))
print(spam(12))
print(spam(0))
print(spam(1))

When trying to divide a number by zero , It will happen ZeroDivisionError. According to the error message

Line number , We know spam() Medium return Statement caused an error .

Function as “ Black box ”

 Usually , For a function , All you need to know is its input value ( Argument ) And output value .
You don't always have to burden yourself , Figure out how the function code actually works .
If you think about functions in this high-level way , Usually people say , You think of this function as a
A black box . This idea is the basis of modern programming .

Mistakes can be made by try and except Statement to handle . Statements that may go wrong are placed in try clause .

If an error occurs , The program execution goes to the next except At the beginning of the clause .

def spam(divideBy):
try:
return 42 / divideBy
except ZeroDivisionError:
print('Error: Invalid argument.')
print(spam(2))
print(spam(12))
print(spam(0))
print(spam(1))

21.0

3.5

Error: Invalid argument.

None

42.0

Please note that , In a function call try In the block , All errors that occur will be caught . Please consider it

The following procedure , It does things differently , take spam() The call is placed in a statement block :

def spam(divideBy):
return 42 / divideBy
try:
print(spam(2))
print(spam(12))
print(spam(0))
print(spam(1))
except ZeroDivisionError:
print('Error: Invalid argument.')

21.0

3.5

Error: Invalid argument.

print(spam(1)) Never executed because , Once executed, skip to except Clause code , Will not return to this document from to try Clause . It will continue to execute downward as usual .

3.8 A little program : Guess the number

# This is a guess the number game.
import random
secretNumber = random.randint(1, 20)
print('I am thinking of a number between 1 and 20.')
# Ask the player to guess 6 times.
for guessesTaken in range(1, 7):# It has a secret number , And give it to the player 6 A chance to guess
print('Take a guess.')
guess = int(input())
if guess < secretNumber:
print('Your guess is too low.')
elif guess > secretNumber:
print('Your guess is too high.')
else:
break # This condition is the correct guess!
if guess == secretNumber:
print('Good job! You guessed my number in ' + str(guessesTaken) + ' guesses!')
else:
print('Nope. The number I was thinking of was ' + str(secretNumber))

Programming questions

print(' Please enter a number !!')
input_name=int(input())
def collatz(num):
if num%2 ==0:
return int(num/2)
else:
return int(num*3+1)
if input_name ==1:
print(input_name)
else:
result = collatz(input_name)
print(result)
while 1:
result = collatz(result)
if result == 1:
print(result)
break
else:
print(result)

Chapter four

Lists and tuples can contain multiple values , This makes it easier to write programs to handle large amounts of data . and , Because the list itself

You can also include other lists , So you can use them to arrange the data into a hierarchy .

4.1 List data type

The list begins with an open square bracket , The right square bracket ends , namely []. The values in the list are also called “ Table item ”. Table entries are separated by commas ( That is to say , They are “ Comma separated ”).

Data types can be arbitrary

4.1.1 Get a single value in the list with a subscript

Subscript from 0 Start

If the number of subscripts used exceeds the number of values in the list ,Python Will give IndexError Error message .

Subscript can only be Integers , Cannot be a floating point value .

4.1.2 Negative subscript

Although subscript from 0 Start and grow up , But you can also use negative integers as subscripts . An integer value −1 Refers to the last subscript in the list ,−2 It refers to the penultimate subscript in the list

4.1.3 Use slice to get sublist

Just as a subscript can get a single value from a list ,“ section ” You can get multiple values from the list , The result is a new list . Slice input in square brackets , Like a subscript , But it has two colon separated integers . Notice the difference between subscript and slice

spam[2] Is a list and subscript ( An integer ).

spam[1:4] It's a list and slice ( Two integers ).

In a slice , The first integer is the subscript at the beginning of the slice . The second integer is the subscript at the end of the slice . Slice up , Up to the value of the second subscript , But not including it .

Left closed right away

4.1.4 use len() Get the length of the list

len() The function returns the number of values in the list passed to it , Just as it can count the number of characters in a string .

>>> len(‘hello’)

5

4.1.5 Use the subscript to change the value in the list

On the left of the assignment statement is a variable name , It's like spam = 4. however , You can also use the index of the list to change the value at the index .

4.1.6 List connection and list replication

+ Operator can connect two lists , Get a new list , Just like it combines two strings into a new string .* Operators can be used for a list and an integer , Copy the list .

>>> [1, 2, 3] + ['A', 'B', 'C']
[1, 2, 3, 'A', 'B', 'C']
>>> ['X', 'Y', 'Z'] * 3
['X', 'Y', 'Z', 'X', 'Y', 'Z', 'X', 'Y', 'Z']
>>> spam = [1, 2, 3]
>>> spam = spam + ['A', 'B', 'C']
>>> spam
[1, 2, 3, 'A', 'B', 'C']

4.1.7 use del Statement to delete a value from the list

del Statement will delete the value at the subscript in the list , All values after the deleted value in the table , Will move forward by one subscript .

>>> spam = ['cat', 'bat', 'rat', 'elephant']
>>> del spam[2]
>>> spam
['cat', 'bat', 'elephant']
>>> del spam[2]
>>> spam
['cat', 'bat']

4.2 Use list

catNames = []
while True:
print('Enter the name of cat ' + str(len(catNames) + 1) +
' (Or enter nothing to stop.):')
name = input()
if name == '':
break
catNames = catNames + [name] # list concatenation
print('The cat names are:')
for name in catNames:
print(' ' + name)

The benefits of using lists are , Now the data is placed in a structure , So the program can process data more flexibly , It is more convenient than putting in some repeated variables .

Be careful : The type should be consistent

4.2.1 The list is used for looping

range(4) The return value of is a list like value .Python Think it's similar to [0, 1, 2, 3].

A common Python skill , Is in for Use in loop range(len(someList)), Iteration list Every subscript of .

>>> supplies = ['pens', 'staplers', 'flame-throwers', 'binders']
>>> for i in range(len(supplies)):
print('Index ' + str(i) + ' in supplies is: ' + supplies[i])
Index 0 in supplies is: pens
Index 1 in supplies is: staplers
Index 2 in supplies is: flame-throwers
Index 3 in supplies is: binders

4.2.2 in and not in The operator

utilize in and not in The operator , You can determine whether a value is in the list . Like other operators ,in and not in Used in expressions , Connect two values : A value to find in the list , And the list to find . These expressions will evaluate to Booleans .

>>> 'howdy' in ['hello', 'hi', 'howdy', 'heyas']
True
>>> spam = ['hello', 'hi', 'howdy', 'heyas']
>>> 'cat' in spam
False
myPets = ['Zophie', 'Pooka', 'Fat-tail']
print('Enter a pet name:')
name = input()
if name not in myPets:
print('I do not have a pet named ' + name)
else:
print(name + ' is my pet.')

4.2.3 Multiple assignment techniques

The multiple assignment technique is a shortcut , Let you in one line of code , Assign values to multiple variables with values in the list .

notes : The number of variables and the length of the list must be strictly equal , otherwise Python Will give ValueError

>>> cat = ['fat', 'black', 'loud']
>>> size, color, disposition = cat
# Equivalent to
>>> cat = ['fat', 'black', 'loud']
>>> size = cat[0]
>>> color = cat[1]
>>> disposition = cat[2]

4.3 Enhanced assignment operation

+= -= *= /= %=

4.4 Method

Methods and functions are one thing , It is simply called on a value . Each data type has its own set of methods . for example , List data types have some useful methods , Used to find 、 add to 、 Delete or operate on values in the list

Both listname.fangfa()

4.4.1 use index() Method to find a value in the list

The subscript used to find a value , If the value is not in the list ,Python Report on ValueError, If there are duplicate values in the list , Just return the subscript it first appeared .

4.4.2 use append() and insert() Method to add a value... To the list

append() Method call , Add parameters to the end of the list .insert() Method can insert a value at any subscript of the list .insert() The first parameter of the method is the subscript of the new value , The second parameter is the new value to insert .

notes :spam = spam.append(‘moose’) and spam = spam.insert(1, ‘chicken’) Make mistakes in writing

append() and insert() The return value of None, The list was modified on the spot

spam.append(‘moose’) and spam.insert(1, ‘chicken’) correct

notes : Method belongs to a single data type .append() and insert() The method is the list method , Can only be raised in the list use , Cannot call... On other values , For example, strings and integers .

4.4.3 use remove() Method to delete a value from the list

remove() Method passes in a value , It will be removed from the called list . Trying to delete a value that does not exist in the list , Will lead to ValueError error .

If the value appears more than once in the list , Only the first value will be deleted .

If you know the subscript of the value you want to delete in the list ,del Statements are easy to use .

>>> spam = [‘cat’, ‘bat’, ‘rat’, ‘elephant’]

>>> spam.remove(‘bat’)

>>> spam

[‘cat’, ‘rat’, ‘elephant’]

4.4.4 use sort() Method to sort the values in the list

reverse The key parameter is True, Give Way sort() In reverse order .spam.sort(reverse=True)

notes : You can't sort a list that has both numbers and string values , because Python I don't know how to compare

they . Otherwise the newspaper TypeError error .

sort() Method to sort a string , Use “ASCII Character order ”, Not the actual dictionary order . This means that uppercase letters come before lowercase letters . So when sorting , Lowercase a In uppercase Z after .

If you need to sort according to the normal dictionary order , It's just sort() Method call , Set the keyword parameter key Set to str.lower

spam.sort(key=str.lower)

4.5Python Exceptions to the indentation rule in

in the majority of cases , The indentation of the code line tells Python Which code block does it belong to . however , There are several exceptions to this rule . For example, in the source code file , A list can actually span a few lines . These lines The indentation of is not important .Python know , You don't see the closing square brackets , The list is not over . also print function

4.6 List like type : Strings and tuples

Lists are not the only data types that represent sequence values . for example , Strings and lists are actually very similar , As long as you think of a string as a list of individual text characters . Many operations on the list , It can also act on strings : Value by subscript 、 section 、 be used for for loop 、 be used for len(), And for in and not in The operator

4.6.1 Variable and immutable data types

But lists and strings are different in one important way . The list is “ Variable ” data type , Its value can be added 、 Delete or change . however , The string is “ Immutable ”, It can't be changed . Try to reassign a character in the string , Will lead to TypeError error .

“ change ” The correct way to a string , Is to use slicing and linking . Construct a “ new ” character string , Copy some parts from the old string .

>>> eggs = [1, 2, 3]
>>> eggs = [4, 5, 6]
>>> eggs
[4, 5, 6]

Although the list value is variable , here eggs The list value in does not change , It's a whole new list of different values ([4, 5, 6]), overwrite The old list value .

[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-LHjL1V1Z-1595908463702)(C:\Users\wpc\Documents\Markdown file \python Programming fast .assets\1594687941977.png)]

4.6.2 Tuple data type

Except for two aspects ,“ Tuples ” The data type is almost the same as the list data type . First , Use parentheses when entering tuples (), Instead of using square brackets []. But the main difference between tuples and lists is , Tuples are like strings , It's immutable . Tuples cannot have their values modified 、 Add or remove .

>>> eggs = ('hello', 42, 0.5)
>>> eggs[1] = 99
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
eggs[1] = 99
TypeError: 'tuple' object does not support item assignment

If there is only one value in the tuple , You can follow the value in parentheses with a comma , Show this situation . otherwise ,Python Will think , You just enter a value in an ordinary bracket . Comma tell Python, This is a tuple ( Unlike other programming languages ,Python After accepting the last entry in a list or tuple The comma following the face )

>>> type(('hello',))
<class 'tuple'>
>>> type(('hello'))
<class 'str'>

Use tuples to tell everyone who reads the code , You're not going to change the value of this sequence . If you need a sequence of values that never change , Just use tuples . The second benefit of using tuples instead of lists is , Because they are immutable , Their content will not change ,Python Some optimizations can be achieved , Make code that uses tuples faster than code that uses lists

4.6.3 use list() and tuple() Function to convert type

function list() and tuple() Returns the list and tuple version of the values passed to them .

If you need a variable version of the tuple value , It's convenient to convert tuples into lists .

>>> tuple(['cat', 'dog', 5])
('cat', 'dog', 5)
>>> list(('cat', 'dog', 5))
['cat', 'dog', 5]
>>> list('hello')
['h', 'e', 'l', 'l', 'o']

4.7 quote

When you assign a list to a variable , In fact, the list of “ quote ” This variable is assigned . A reference is a value , Point to some data . A list reference is a value that points to a list .

>>> **spam = [0, 1, 2, 3, 4, 5]**
>>> **cheese = spam**
>>> **cheese[1] = 'Hello!'**
>>> **spam**
[0, 'Hello!', 2, 3, 4, 5]
>>> **cheese**
[0, 'Hello!', 2, 3, 4, 5]

remember , Variables are like boxes of values . Because the list variable doesn't actually contain a list , It contains a list of “ quote ”( These references contain ID Numbers ,Python Use these internally ID, But you can ignore ).

Variables contain references to list values , Not the list value itself . But for strings and integer values , Variable Contains a string or integer value . When a variable must hold a value of a variable data type , For example, a list or dictionary , Python Just use references . For values of immutable data types , Like strings 、 Integer or tuple ,Python Variables hold the value itself . although Python Variables technically contain references to list or dictionary values , But people often say casually , This variable contains a list or dictionary

4.7.1 Pass on references

To understand how parameters are passed to functions , Quotation is especially important . When a function is called , The value of the parameter is copied to the argument . For a list of ( And dictionaries ), This means that the argument gets a copy of the reference .

def eggs(someParameter):
someParameter.append('Hello')
spam = [1, 2, 3]
eggs(spam)
print(spam)

Please note that , When eggs() When called , The return value is not used for spam Assign new values to . contrary , It directly modifies the list on the spot .

[1, 2, 3, ‘Hello’]

Even though spam and someParameter Contains different references , but They all point to the same list . That's why in a function append(‘Hello’) Method call after function call returns , Will still have an impact on the list .

4.7.2 copy Modular copy() and deepcopy() function

When dealing with lists and dictionaries , Although passing references is often the most convenient way , But if the function modifies the passed in list or dictionary , You may not want these changes to affect the original list or dictionary . Do that ,Python Provided is called copy Module , It includes copy() and deepcopy() function .

copy.copy(), Can be used to Copy variable values such as lists or dictionaries , Instead of just copying references .

[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-K9wY1Uj3-1595908463711)(C:\Users\wpc\Documents\Markdown file \python Programming fast .assets\1594905544970.png)]

copy.deepcopy() Function usage conditions : The copied list contains the list ,deepcopy() Functions will also copy their internal lists .

import copy
origin = [1, 2, [3, 4]]
#origin There are three elements in it :1, 2,[3, 4]
cop1 = copy.copy(origin)
cop2 = copy.deepcopy(origin)
# cop1 Whether or not cop2 Same content
print(cop1 == cop2)
#True
# cop1 Whether or not cop2 For the same reference
print(cop1 is cop2)
#False
#cop1 and cop2 It looks the same , But it's no longer the same object
origin[2][0] = "hey!"
origin[1]='wpc'
print(origin)
print(cop1)
print(cop2)
# hold origin The son inside list [3, 4] Changed an element , Observe cop1 and cop2

4.8 Summary

The list is variable , This means that their content can be changed . Tuples and strings are like lists in some ways , But it's immutable , Cannot be modified . A variable that contains a tuple or string , Can be overwritten by a new tuple or string , But this is not the same thing as modifying the original value on site , Unlike append() and remove() Effect of method on list .

Variables do not directly save list values , They hold a list of “ quote ”. When copying variables or using lists as arguments to function calls , This is important . Because what is copied is only a list reference , So pay attention to , Any changes to this list may affect other variables in the program . If you need to modify the list in a variable , Without modifying the original list , You can use it copy() or deepcopy().

copy.copy() The function will shallow copy the list , and copy.deepcopy() Function will make a deep copy of the list . in other words , Only copy.deepcopy() All lists in the list will be copied .

end keyword

keyword end Can be used to output results to the same line , Or add different characters at the end of the output

end The function is to b Add something to the back

a, b = 0, 1
while b < 1000:
print(b, end=',')
a, b = b, a+b

result 1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,

4.9 Project practice

1. Suppose there is a list like this :

spam = [‘apples’, ‘bananas’, ‘tofu’, ‘cats’]

Write a function , It takes a list value as an argument , Returns a string . The string contains all

With table items , Items are separated by commas and spaces , And insert... Before the last table entry and. for example , take

Ahead spam The list is passed to the function , Will return ’apples, bananas, tofu, and cats’. But your function should

The can handle any list passed to it .

def charu(LIST):
length = len(LIST)
count = 0
zifuchuan=''
for inx, val in enumerate(LIST):
if inx == length - 1:
zifuchuan = zifuchuan + 'and ' + val
return zifuchuan
zifuchuan=zifuchuan+val+','
spam = ['apples','bananas','tofu','cats','wpc']
print(charu(spam))

[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-3dIbo3B7-1595908463719)(C:\Users\wpc\Documents\Markdown file \python Programming fast .assets\1594993782606.png)]

def PRINT(LIST):
Row=len(LIST)
Colum=len(LIST[1])
print(' The list Behavior ' + str(Row))
print(' The list As a ' + str(Colum))
for i in range(Colum) :
for j in range(Row):
print(LIST[j][i],end='')
if j>=Row-1 :
print('')
grid = [['.', '.', '.', '.', '.', '.'],
['.', 'O', 'O', '.', '.', '.'],
['O', 'O', 'O', 'O', '.', '.'],
['O', 'O', 'O', 'O', 'O', '.'],
['.', 'O', 'O', 'O', 'O', 'O'],
['O', 'O', 'O', 'O', 'O', '.'],
['O', 'O', 'O', 'O', '.', '.'],
['.', 'O', 'O', '.', '.', '.'],
['.', '.', '.', '.', '.', '.']]
PRINT(grid)

The fifth chapter Dictionaries and structured data

5.1 Dictionary data type

Like a list ,“ Dictionaries ” It's a collection of values . But unlike the subscript of the list , The index of the dictionary can

Use many different data types , It's not just integers . The index of the dictionary is called “ key ”, Key and its associated value

be called “ key - value ” Yes . In the code , Dictionary input with curly braces {}.

myCat = {‘size’: ‘fat’, ‘color’: ‘gray’, ‘disposition’: ‘loud’}

These values can be accessed through their keys

>>> myCat[‘size’]

‘fat’

>>> 'My cat has ’ + myCat[‘color’] + ’ fur.'

‘My cat has gray fur.’

Dictionaries can still use integer values as keys , Just as a list uses integer values as subscripts , But they don't

Must follow 0 Start , It can be any number .

>>> spam = {12345: ‘Luggage Combination’, 42: ‘The Answer’}

5.1.1 Dictionaries and lists

It's not like a list , The entries in the dictionary are not sorted . be known as spam List of , The first entry is spam[0]. But not in the dictionary “ first ” Table item . Although when determining whether the two lists are the same , The order of entries is important , But in the dictionary , key - Values are not important to the order of input , Because dictionaries are not sorted , So you can't slice like a list .

>>> spam = [‘cats’, ‘dogs’, ‘moose’]

>>> bacon = [‘dogs’, ‘moose’, ‘cats’]

>>> spam == bacon

False

>>> eggs = {‘name’: ‘Zophie’, ‘species’: ‘cat’, ‘age’: ‘8’}

>>> ham = {‘species’: ‘cat’, ‘age’: ‘8’, ‘name’: ‘Zophie’}

>>> eggs == ham

True

5.1.2 keys()、values() and items() Method

Yes 3 A dictionary method , They will return values similar to lists , The key corresponding to the dictionary 、 Values and keys - It's worth it :keys()、values() and items(). The values returned by these methods are not real lists , They can't be modified , No, append() Method . But these data types ( Namely dict_keys、dict_values and dict_items) It can be used for for loop .

>>> spam = {‘color’: ‘red’, ‘age’: 42}

>>> for v in spam.values():

print(v)

red

42

here ,for The loop iterates spam Every value in the dictionary .for Loops can also iterate over each key , Or key - It's worth it :

>>> for k in spam.keys():

print(k)

color

age

>>> for i in spam.items():

print(i)

(‘color’, ‘red’)

(‘age’, 42)

If you want to get a real list through these methods , Pass the return value of a similar list to list function .

>>> spam = {‘color’: ‘red’, ‘age’: 42}

>>> spam.keys()

dict_keys([‘color’, ‘age’])

>>> list(spam.keys())

[‘color’, ‘age’]

Using the technique of multiple assignment , stay for Loop to assign keys and values to different variables .

>>> spam = {‘color’: ‘red’, ‘age’: 42}

>>> for k, v in spam.items():

print('Key: ’ + k + ’ Value: ’ + str(v))

Key: age Value: 42

Key: color Value: red

5.1.3 Check the dictionary for keys or values

in and not in Operators can check whether values exist in lists and dictionaries .

>>> spam = {‘name’: ‘Zophie’, ‘age’: 7}

>>> ‘name’ in spam.keys()

True

>>> ‘Zophie’ in spam.values()

True

>>> ‘color’ in spam.keys()

False

>>> ‘color’ not in spam.keys()

True

>>> ‘color’ in spam

False

Be careful :‘color’ in spam In essence, it is an abbreviated version . amount to ’color’ in spam.keys()

5.1.4 get() Method

Before accessing the value of a key , Check if the key exists in the dictionary , It's troublesome . Fortunately , The dictionary has a get() Method , It has two parameters : The key to get its value , And if the key does not exist , Alternate value returned .

picnicItems = {‘apples’: 5, ‘cups’: 2}

’I am bringing ’ + str(picnicItems.get(‘eggs’, 0)) + ’ eggs.'

‘I am bringing 0 eggs.’

because picnicItems There is no... In the dictionary ’egg’ key ,get() The default value returned by the method is 0. Don't use get(), The code will generate an error message , Like the following example :

>>> 'I am bringing ’ + str(picnicItems[‘eggs’]) + ’ eggs.'

Traceback (most recent call last):

File “<pyshell#34>”, line 1, in

‘I am bringing ’ + str(picnicItems[‘eggs’]) + ’ eggs.’

KeyError: ‘eggs’

5.1.5 setdefault() Method

setdefault() Method provides a way , Do this in one line . The first parameter passed to the method , Is the key to check . The second parameter , Is the value to be set if the key does not exist . If the key does exist , Method will return the value of the key .

>>> spam = {‘name’: ‘Pooka’, ‘age’: 5}

>>> spam.setdefault(‘color’, ‘black’)

‘black’

>>> spam

{‘color’: ‘black’, ‘age’: 5, ‘name’: ‘Pooka’}

>>> spam.setdefault(‘color’, ‘white’)

‘black’

>>> spam

{‘color’: ‘black’, ‘age’: 5, ‘name’: ‘Pooka’}

setdefault() Method is a good shortcut , You can ensure that a key exists .

Example

message = 'It was a bright cold day in April, and the clocks were striking thirteen.'
count = {}
for character in message:
count.setdefault(character, 0)
count[character] = count[character] + 1
print(count)

Count the frequency of words

result {‘I’: 1, ‘t’: 6, ’ ': 13, ‘w’: 2, ‘a’: 4, ‘s’: 3, ‘b’: 1, ‘r’: 5, ‘i’: 6, ‘g’: 2, ‘h’: 3, ‘c’: 3, ‘o’: 2, ‘l’: 3, ‘d’: 3, ‘y’: 1, ‘n’: 4, ‘A’: 1, ‘p’: 1, ‘,’: 1, ‘e’: 5, ‘k’: 2, ‘.’: 1}

5.2 Beautiful printing

Import pprint modular , You can use pprint() and pformat() function , They will “ Beautiful printing ” A dictionary word . If you want the display ratio of table items in the dictionary print() The output is cleaner , This is useful .

import pprint
message = 'It was a bright cold day in April, and the clocks were striking
thirteen.'
count = {}
for character in message:
count.setdefault(character, 0)
count[character] = count[character] + 1
pprint.pprint(count)

The dictionary itself contains nested lists or dictionaries ,pprint.pprint() Functions are particularly useful .

Want to get beautifully printed text as a string , Not on the screen , It is called pprint.pformat()

pprint.pprint(someDictionaryValue)

print(pprint.pformat(someDictionaryValue))

5.3 Use data structures to model the real world

5.3.1 Tic tac toe chessboard

theBoard = {'top-L': 'O', 'top-M': 'O', 'top-R': 'O', 'mid-L': 'X', 'mid-M':
'X', 'mid-R': ' ', 'low-L': ' ', 'low-M': ' ', 'low-R': 'X'}
def printBoard(board):
print(board['top-L'] + '|' + board['top-M'] + '|' + board['top-R'])
print('-+-+-')
print(board['mid-L'] + '|' + board['mid-M'] + '|' + board['mid-R'])
print('-+-+-')
print(board['low-L'] + '|' + board['low-M'] + '|' + board['low-R'])
printBoard(theBoard)

5.3.2 Nested dictionaries and lists

When modeling complex things , You may find that dictionaries and lists need to include other dictionaries and lists . The list applies to packages

Contains an ordered set of values , Dictionaries are suitable for containing associated keys and values

allGuests = {'Alice': {'apples': 5, 'pretzels': 12},
'Bob': {'ham sandwiches': 3, 'apples': 2},
'Carol': {'cups': 3, 'apple pies': 1}}
def totalBrought(guests, item):
numBrought = 0
for k, v in guests.items():
numBrought = numBrought + v.get(item, 0)
return numBrought
print('Number of things being brought:')
print(' - Apples ' + str(totalBrought(allGuests, 'apples')))
print(' - Cups ' + str(totalBrought(allGuests, 'cups')))
print(' - Cakes ' + str(totalBrought(allGuests, 'cakes')))
print(' - Ham Sandwiches ' + str(totalBrought(allGuests, 'ham sandwiches')))
print(' - Apple Pies ' + str(totalBrought(allGuests, 'apple pies')))

Programming tasks

def displayInventory(inventory):
print("Inventory:")
item_total = 0
for k, v in inventory.items():
print(str(v) + ' ' + k)
item_total += v
print("Total number of items: " + str(item_total))
def addToInventory(inventory, addedItems):
for i in addedItems:
if i in inventory :
inventory[i]=inventory[i]+1
else:
inventory.setdefault(i, 1)
return inventory
inv = {'gold coin': 42, 'rope': 1}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
inv = addToInventory(inv, dragonLoot)
displayInventory(inv)

2.{‘foo’: 42}

3. Items stored in the dictionary are unordered , The items in the list are ordered .

4. You'll get KeyError error .

5. There is no difference between .in Operator to check whether a value is a key in the dictionary .

6.‘cat’ in spam Check if there is a in the dictionary ‘cat’ key , and ’cat’ in spam.values() The check is

No there is a value ‘cat’ Corresponding to spam A key in .

7.spam.setdefault(‘color’, ‘black’)

8.pprint.pprint()

Chapter six String manipulation

6.1 Processing strings

6.1.1 Literal of a string

Strings start and end in single quotes

6.1.2 Double quotes

Strings can start and end in double quotes , It's like using single quotes . One benefit of using double quotes , That is, single quotation marks can be used in strings .

6.1.3 Escape character

Escape character Print as ’ Single quotation marks " Double quotes \t tabs \n A newline \ Backslash

6.1.4 Original string

You can precede the quotation mark at the beginning of the string with r, Make it the original string .“ Original string ” Ignore all escape characters at all , Print out all the backslashes in the string .

>>> print(r’That is Carol’s cat.’)

That is Carol’s cat.

6.1.5 Multiline string with triple quotes

stay Python in , The start and end of a multiline string are 3 A single quotation mark or 3 Double quotes .“ Triple quotes ” All quotation marks between 、 A tab or line break , Are considered part of a string .Python The code block indentation rule of does not apply to multiline strings .

print('''Dear Alice,
Eve's cat has been arrested for catnapping, cat burglary, and extortion.
Sincerely,
Bob''')

result :

Dear Alice,

Eve’s cat has been arrested for catnapping, cat burglary, and extortion.

Sincerely,

Bob

Eve’s Single quote characters in do not need to be escaped . In the original string , Escaping single and double quotation marks is optional .

6.1.6 Multiline comment

Although the pound sign character (#) This line is a comment , But multiline strings """ Often used as a multiline comment .

"""This is a test Python program.
Written by Al Sweigart [email protected]
This program was designed for Python 3, not Python 2.
"""

6.1.7 String subscripts and slices

>>> spam = 'Hello world!'
>>> spam[0]
'H'
>>> spam[4]
'o'
>>> spam[-1]
'!'
>>> spam[0:5]
'Hello'
>>> spam[:5]
'Hello'
>>> spam[6:]
'world!'

Please note that , String slicing does not modify the original string . You can get slices from a variable , Record in another variable .

6.1.8 A string of in and not in The operator

Test the first string ( Exactly match , Case sensitive ) Whether in the second string .

6.2 Useful string methods

6.2.1 String method upper()、lower()、isupper() and islower()

upper() and lower() The string method returns a new string , All letters of the original string are converted to uppercase or lowercase accordingly . Non alphabetic characters in the string remain unchanged .

If you need to make a case independent comparison ,upper() and lower() The method is very useful .

print('How are you?')
feeling = input()
if feeling.lower() == 'great':
print('I feel great too.')
else:
print('I hope the rest of your day is good.')

If the string has at least one letter , And all letters are uppercase or lowercase ,isupper() and islower() Method will return a Boolean value accordingly True. Determine whether the strings are all uppercase or lowercase

6.2.2 isX String method

 isalpha() return True, If the string contains only letters , And not empty ;

 isalnum() return True, If the string contains only letters and numbers , And not empty ;

 isdecimal() return True, If the string contains only numeric characters , And not empty ;

 isspace() return True, If the string contains only spaces 、 Tabs and line breaks , And not empty ;

 istitle() return True, If the string contains only characters that begin with uppercase letters 、 Words with lowercase letters after them .

If you need to validate user input ,isX String methods are useful .

6.2.3 String method startswith() and endswith()

Check whether the beginning or end of a string is equal to another string , Not the whole string

If consistent startswith() and endswith() Method returns True, If the string they call is passed in this method

The start or end of a string . otherwise , Method returns False.

6.2.4 String method join() and split()

If you have a list of strings , They need to be connected , Become a separate string ,join() The method is very useful .join() Method calls on a string , The parameter is a list of strings , Returns a string . The returned string is concatenated from each string in the incoming list .

>>> ', '.join(['cats', 'rats', 'bats'])
'cats, rats, bats'
>>> ' '.join(['My', 'name', 'is', 'Simon'])
'My name is Simon'
>>> 'ABC'.join(['My', 'name', 'is', 'Simon'])
'MyABCnameABCisABCSimon'

Remember ,join() Method is called for a string , And pass in a list value ( It's easy to accidentally call it in other ways ).split() Method does exactly the opposite : It calls... Against a string , Returns a list of strings .

>>> 'My name is Simon'.split()
['My', 'name', 'is', 'Simon']

character string ’My name is Simon’ Split according to various white space characters , Such as spaces 、 Tab or newline . These white space characters are not included in the string that returns the list . Also you can ask the split() Method to pass in a split string , Specifies that it is divided into different strings .

>>> 'MyABCnameABCisABCSimon'.split('ABC')
['My', 'name', 'is', 'Simon']
>>> 'My name is Simon'.split('m')
['My na', 'e is Si', 'on']

6.2.5 use rjust()、ljust() and center() Method to align text

rjust() and ljust() String methods return a populated version of the string that calls them , Align text by inserting spaces . The first argument to both methods is an integer length , Used to align strings .

>>> 'Hello'.rjust(10)
' Hello'
>>> 'Hello'.rjust(20)
' Hello'
>>> 'Hello World'.rjust(20)
' Hello World'
>>> 'Hello'.ljust(10)
'Hello

rjust() and ljust() The second optional parameter of the method specifies a padding character , Replace the space character .

>>> 'Hello'.rjust(20, '*')
'***************Hello'
>>> 'Hello'.ljust(20, '-')
'Hello---------------'

center() String method and ljust() And rjust() similar , But it centers the text , Not left or right .

If you need to print tabular data , Leave the correct space , These methods are particularly useful .

def printPicnic(itemsDict, leftWidth, rightWidth):
print('PICNIC ITEMS'.center(leftWidth + rightWidth, '-'))
for k, v in itemsDict.items():
print(k.ljust(leftWidth, '.') + str(v).rjust(rightWidth))
picnicItems = {'sandwiches': 4, 'apples': 12, 'cups': 4, 'cookies': 8000}
printPicnic(picnicItems, 12, 5)
printPicnic(picnicItems, 20, 6)

6.2.6 use strip()、rstrip() and lstrip() Delete white space characters

Delete the left side of the string 、 White space characters on the right or both sides ( Space 、 Tabs and line breaks ).strip() The string method will return a new string , It has no white space at the beginning or end . lstrip() and rstrip() Method will delete the blank characters on the left or right accordingly .

>>> spam = ' Hello World '
>>> spam.strip()
'Hello World'
>>> spam.lstrip()
'Hello World '
>>> spam.rstrip()
' Hello World'

towards strip() Method to pass in parameters ’ampS’, Tell it Both ends of the string stored in the variable , Delete the occurrence of a、m、p And capital S. Pass in strip() Method , The order of the characters is not important :strip(‘ampS’) What to do and strip(‘mapS’) or strip(‘Spam’) equally .

>>> spam = 'SpamSpamBaconSpamEggsSpamSpam'
>>> spam.strip('ampS')
'BaconSpamEggs'

6.2.7 use pyperclip Module copy and paste string

pyperclip Module has copy() and paste() function , You can send text to your computer's clipboard , Or receive text from it . Send the output of the program to the clipboard , Make it easy to paste into mail 、 In a word processor or other software .pyperclip Modules are not Python Self contained . To install it

6.3 Project password safe deposit box

PASSWORDS = {'email': 'F7minlBDDuvMJuxESSKHFhTxFtjVB6',
'blog': 'VmALvQyKAxiVH5G8v01if1MLZF3sdt',
'luggage': '12345'}
import sys, pyperclip
# Determine whether there is a problem with the input parameters helloworld.py blog
if len(sys.argv) < 2:
print('Usage: py pw.py [account] - copy account password')
sys.exit()
# Pass the query key to account
account = sys.argv[1] # first command line arg is the account name
if account in PASSWORDS:# Query whether there is account Key
pyperclip.copy(PASSWORDS[account])
# Copy to clipboard
print('Password for ' + account + ' copied to clipboard.')
else:
print('There is no account named ' + account)

Start command :helloworld.py blog

6.4 Change the clipboard contents into an unordered list

import pyperclip
text = pyperclip.paste()
# Separate lines and add stars.
lines = text.split('\n')
for i in range(len(lines)): # loop through all indexes for "lines" list
lines[i] = '* ' + lines[i] # add star to each string in "lines" list
text = '\n'.join(lines)
pyperclip.copy(text)

1. Escape characters represent some characters in a string , These characters are hard to type in the code in other ways .
2.\n Is a newline ,\t Is tab .
3.\ The escape character represents a backslash .
4.Howl’s There is no problem with single quotation marks in , Because you use double quotation marks to identify the beginning and end of the string .
5. Multiline strings let you use newline characters in strings , Not necessarily \n Escape character .
6. These expressions evaluate to the following values :
• ‘e’
• ‘Hello’
• ‘Hello’
• 'lo world!
7. These expressions evaluate to the following values :
• ‘HELLO’
• True
• ‘hello’
8. These expressions evaluate to the following values :
• [‘Remember,’, ‘remember,’, ‘the’, ‘fifth’, ‘of’, ‘November.’]
• ‘There-can-be-only-one.’
9. Use them separately rjust()、ljust() and center() String method .
10.lstrip() and rstrip() Method removes white space characters from the left and right sides of a string, respectively .

Programming operation

def printTable(tableData):
colWidths = [0] * len(tableData)
for i in range(len(colWidths)):
colWidths[i] = max(len(tableData[i][0]), len(tableData[i][1]), len(tableData[i][2]), len(tableData[i][3]))
for j in range(len(tableData[0])):
for k in range(len(tableData)):
print(tableData[k][j].rjust(colWidths[k]),end=' ')
print()
tableData = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']]
printTable(tableData)

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved