"Python quick programming to get started and automate tedious work" learning summary - the first part of python programming basics

Table of contents

Table of contents

foreword

Chapter 1 Python Basics

1.1 Operators and data types

1.2 String concatenation (+) and copying (*)

1.3 Assignment (=), equal to (==)

1.4 Variable names

1.5 Internal functions

Chapter 2 Control Flow

2.1 Boolean (True/False)

2.2 Comparison Operators, Boolean Operators

2.3 Control Flow Statements

2.4 Importing modules

2.5 sys.exit(): end the program early

Chapter 3 Functions

3.1 def statement and parameters

3.2 None value (no value, NoneType data type)

3.3 Local and global scope

3.4 global statement

3.5 Exception handling try... except...

Chapter 4 Lists list[]

4.1 Get a single value in the list: list[index]

4.2 Slicing to obtain sublists: list[:]

4.3 The len(list) function obtains the list length, in, not in

4.4 Changing the value of a list element

4.5 List concatenation (+), list copy (*), multiple assignment, enhanced assignment

4.6 Find the subscript of a list value: the index() method

4.7 Delete the value in the list: del statement, remove() method, pop() method

4.8 Inserting list values: insert(), append() methods

4.9 Sorting list values: sort(), reverse() methods

4.10 String str, tuple()

4.11 List and tuple types convert list(), tuple()

4.12 Reference: copy(), deepcopy() functions

Chapter 5 Dictionaries dict{} and Structured Data

5.1 字典、dict.keys()、dict.values()、dict.items()

5.2 get() method, setdefault() method

5.3 pprint(), pformat() function

Chapter 6 String Manipulation

6.1 Handling strings

6.2 String subscript, slice, in, not in operators

6.3 Useful string methods


foreword

Learn the summary of the first part of "Python quick programming to automate tedious work", some of which are not organized according to the book catalogue.

22/3/17 Supplement: The Chinese version I studied is the first version, but there is already a second version in English in 2019, and Chinese is also available now. It is a bit slow to read English. This study note is based on the second version. I recommend it .

[python automates tedious work] directory

The official video of the second edition is also recommended.

Douban score 9.6 Python God Book, 578 pages of Python programming to get started quickly, zero-based Xiaobai Gospel_哔哩哔哩_bilibili

Online book reference for the second edition in English:

Automate the Boring Stuff with Python

On the whole, the second edition has more Chapter 8 Input Validation and Chapter 14 Processing Google Sheets than the first edition.

In the detail part, some new modules are used: such as pyinputplus, etc.


Chapter 1 Python Basics

1.1 Operators and data types

operator illustrate operator illustrate
** index +、- add, subtract
% modulo/remainder * 、/ multiply, divide
// Divisibility/quotient rounding
type of data example
integer int -2, -1, 0, 1, 88
floating point float -1.0, 1.34, 0.0, --0.5(=0.5)
string string str 'a','A','Abddf','11 cats!'

1.2 String concatenation (+) and copying (*)

"Alice" + "Bob" AliceBob

"Alice"*3 AliceAliceAlice

TypeError case :

String + number: "Alice" + 12, if necessary, use str() to convert 12 into a string, "Alice" + str(12)

String *String: *"Alice1" * "Alice2"

String * Float: "Alice" * 5.0

1.3 Assignment (=), equal to (==)

Spam = 2 spam --> 2

Spam == 2 --> True

1.4 Variable names

  • only one word

  • Can only contain letters, numbers, underscores

  • cannot start with a number

  • Convention : start with a lowercase letter, camelCase

1.5 Internal functions

(1) Notes

# : Comment out the code following this line

\: continuation character

 print('For your ' + \
      'infomation')
 # For your infomation
 ​
 msg1 = '''维护
   秩序!
 '''
 """
 维护
     秩序!
     
 """
 print(msg1)
 msg2 = """ni
   w
     ****"""
 print(msg2)
 """
 ni
     w
         ****
 """

(2) print():

Display the string inside () to the screen

Keyword arguments have optional arguments end, sep:

  • end: what to print at the end of the argument

  • sep: what to print between arguments 

print("a","b","c",sep=',',end='...')  # a,b,c...

(3) input():

Wait for the user to enter some text from the keyboard, and the return value is a string

(4) len():

Evaluates an integer, the number of string characters in ()

(5) str()、int()、float():

Convert the incoming value into a string, integer, or floating-point number.

If a value that cannot be evaluated as an integer is passed to int(), an error will be reported, such as int('99.9') and int('one').

int(7.9) --> 7

Chapter 2 Control Flow

2.1 Boolean (True/False)

Capitalization cannot be wrong! Cannot be used as a variable name.

2.2 Comparison Operators, Boolean Operators

Comparison operators evaluate to True or False.

comparison operator illustrate comparison operator illustrate
== equals (for all datatype values) <、> less than, greater than (integer, floating point values ​​only)
!= not equal (for all data type values) <=、>= Less than or equal to, greater than or equal to (only for integer and floating point values)
boolean operator illustrate boolean operator illustrate
and A binary Boolean operator that evaluates to true if both are true. True and False --> False not Unary boolean operator, not True --> False
or Binary Boolean operators, one is true and the result is true. True or False --> True

Order of operations: Arithmetic and comparison operator evaluation --> not operator --> and operator --> or operator.

2.3 Control Flow Statements

(1) if statement

 if 条件(求值为True或False的表达式):
     代码块
 if 条件(求值为True或False的表达式):
     代码块1
 else:
     代码块2
 if 条件1(求值为True或False的表达式):
     代码块2
 elif 条件2(求值为True或False的表达式):
     代码块2
 elif ...:
   ...
 else:
     代码块n
  • If there is a series of elif statements, only one or zero or execute, once the condition of one statement is True, other elif statements will be skipped automatically.

(2) while loop statement (break, continue):

while 条件(求值为True或False的表达式):
     代码块

break : Jump out of the while loop ahead of time, and then execute the statement after while.

continue : Used inside the loop, immediately call back to the beginning of the loop, and re-evaluate the loop condition.

(3) for loop, range() function:

A for loop and a while loop can do the same thing, but the for loop is more concise.

The three parameters of range include the start value and do not contain the end value.

 for 变量 in range(起始、停止、步长):
     代码块 
 -------------------------
 for i in range(4):        # 0 1 2 3
   print(i)
 for j in range(4,7):      # 4 5 6
   print(j)
 for k in range(1,9,3):    # 1 4 7
   print(k)
 for h in range(10,1,-3):    # 10  7 4
   print(h)

2.4 Importing modules

 import 模块1,模块2
 -------------------------
 import random
 j = random.randint(1,100) # 随机取1-100之间的整数,包含1和100
 =========================
 from 模块1 import *
 -------------------------
 from random import *
 j = randint(1,100) # 可直接调用函数,不写模块名前缀,但可读性不如前者

2.5 sys.exit(): end the program early

sys.exit() allows the program to terminate and exit, in the sys module.

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

Chapter 3 Functions

3.1 def statement and parameters

Variables passed into a function are discarded after the program ends!

 def hello(变元/变量):
   代码块
   return 返回值/表达式

3.2 None value (no value, NoneType data type)

The return value of the print() function is None.

3.3 Local and global scope

  • Code at global scope cannot use any local variables

  • Local scope can access global variables

  • Code in a function's local scope cannot use variables in other local scopes

  • Different scopes can use the same name for different variables.

  • Do not rely too much on global variables. When the program is large, it is difficult to track the defect location of variable assignment

3.4 global statement

If you need to modify a global variable within a function, use the global statement.

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

Determine whether a variable is a local variable or a global variable:

  • Global variables: Variables are used in the global scope, there is a global statement for the variable in a function, there is no global statement for the variable in the function, and there are also assignment statements.

  • Local variable: There is no global statement for this variable in the function, and it is used for assignment statement.

3.5 Exception handling try... except...

Once execution jumps to the except clause code, it does not go back to the try clause. The code after the try error code will not be executed.

 def spam(divideBy):
   try:
     return 43/divideBy
   except ZeroDivisionError:       # 除数为零异常
     print('Error:Invalid argument.')

Chapter 4 Lists list[]

4.1 Get a single value in the list: list[index]

By subscript index, index can only be an integer, such as list[-1], list[0], list[2], and cannot be a floating point value.

Negative subscripts represent the reciprocal, such as -1 is the last subscript, -2 is the penultimate subscript

 list = [1,3,5,6,7]
 print(list[-1],list[0],list[2])   # 7 1 5

Lists can nest lists.

 list = [1,3,[5,7,8],1,1,2]
 print(list[-1],list[0],list[2]) #2  1 [5,7,8]
 print(list[2][2])   # 8

4.2 Slicing to obtain sublists: list[:]

list[start value:stop value:step]: contains the value of the start value subscript in the list, but does not include the value of the end value subscript.

 list = [1,3,5,6,7,11,14,16,18]
 print(list[1:3])    # [3,5]
 print(list[:3])     # [1,3,5]
 print(list[7:])     # [16,18]
 print(list[1:6:2])  # [3,6,11]
 print(list[::3])    # [1, 6, 14]

4.3 The len(list) function obtains the list length, in, not in

  • Lookup Values ​​in Lookup List: Returns Boolean, value in list returns True

  • Lookup value not in Lookup list: Returns Boolean, value not in list returns True

 list = [1,3,5,6,7,11,14,16,18]
 print(len(list))    # 9
 ​
 for i in range(len(list)):
   print(i)

4.4 Changing the value of a list element

 list = [1,3,5,6,7,11,14,16,18]
 list[0] = 99
 print(list)   # [99,3,5,6,7,11,14,16,18]

4.5 List concatenation (+), list copy (*), multiple assignment, enhanced assignment

The * operator works on a list and an integer.

The values ​​in the list can be copied to multiple variables, and the number of variables must be strictly equal to the length of the list, otherwise ValueError will be thrown.

 list1,list2 = [1,2,3],[4,5,6,7]
 print(list1 + list2)    # [1, 2, 3, 4, 5, 6, 7]
 print(list1 * 3)        # [1, 2, 3, 1, 2, 3, 1, 2, 3]
 a,b,c = list1
 print(a,b,c)      # 1 2 3
assignment statement equivalent statement assignment statement equivalent statement
spam += 1 spam = spam + 1 spam /= 1 spam = spam / 1
spam -= 1 spam = spam - 1 spam %= 1 spam = spam % 1
spam *= 1 spam = spam * 1
 a = 'AFDGF'
 a += "abdbf"
 print(a)  # AFDGFabdbf
 b = ['Mood']
 b *= 3
 print(b)    # ['Mood','Mood','Mood']

4.6 Find the subscript of a list value: the index() method

If the value is not in the list, raise ValueError.

If there are multiple values ​​in the list, return the index of the first occurrence.

 a = ['hello','wird','hahahah','wird','hahahah']
 i1 = a.index('hello')
 print(i1)   # 0
 i2 = a.index('wird')
 print(i2)   # 1

4.7 Delete the value in the list: del statement, remove() method, pop() method

Use del if you know the subscript, and remove if you know the value.

  • del list[index] : Delete the value whose subscript is index in the list, index is an integer, and can also be deleted by slice.

  • list.remove('cat'): Delete the specified value. If the value appears multiple times, only the first occurrence will be deleted.

  • list.pop(): delete the last element of the list

 list = [1,3,5,6,7,11,14,16,18]
 del list[0]
 print(list)   # [3,5,6,7,11,14,16,18]
 del list[0:3]
 print(list)   # [7,11,14,16,18]
 del list[::2]
 print(list)   # [11, 16]
 list.pop()
 print(list)   # [11]
 ​
 list1 = ['cat','bga','cat','cat']
 list1.remove('cat')
 print(list1)  # ['bga','cat','cat']

4.8 Inserting list values: insert(), append() methods

The return value of insert() and append() methods is None, and the list is directly modified.

Can only be called on lists, not on other values ​​such as strings.

  • append(): add the parameter at the end of the list

  • insert(new value subscript, insert new value): add the new value at the specified subscript position

 list = ['a','b','c']
 list.append('hello')
 print(list)   # ['a','b','c','hello']
 list.insert(3,'d')
 print(list)   # ['a','b','c','d','hello']

4.9 Sorting list values: sort(), reverse() methods

It is not possible to sort a list that contains both numbers and strings, such as [1,3,'a'] cannot be sorted! !

  • sort(): Sorts a list of values ​​or strings in ASCII code order . Numbers (string format) first, then uppercase letters, then lowercase letters.

  • sort(key=str.lower): Sort in alphabetical order, the same letter is uppercase first and then lowercase. Treats all as lowercase when sorting, but doesn't actually change the list values.

  • sort(reverse = True): Sort the list of values ​​​​or strings in reverse order of ASCII code characters .

  • reverse(): Sort the list in reverse order.

 a = ['egg', 'a', 'A', 'Gigg', 'Zippo', '!!', '@', 'zIPPO', '112', '9', '2.3', '-3.8', '?']
 a.sort()
 print(a)   # ['!!', '-3.8', '112', '2.3', '9', '?', '@', 'A', 'Gigg', 'Zippo', 'a', 'egg', 'zIPPO']
 -----------------------------------------------
 a = ['egg', 'a', 'A', 'Gigg', 'Zippo', '!!', '@', 'zIPPO', '112', '9', '2.3', '-3.8', '?']
 a.sort(key=str.lower)
 print(a)   # ['!!', '-3.8', '112', '2.3', '9', '?', '@', 'a', 'A', 'egg', 'Gigg', 'Zippo', 'zIPPO']
 -----------------------------------------------
 a = ['egg', 'a', 'A', 'Gigg', 'Zippo', '!!', '@', 'zIPPO', '112', '9', '2.3', '-3.8', '?']
 a.sort(reverse = True)
 print(a)   # ['zIPPO', 'egg', 'a', 'Zippo', 'Gigg', 'A', '@', '?', '9', '2.3', '112', '-3.8', '!!']
 -----------------------------------------------
 a = ['egg', 'a', 'A', 'Gigg', 'Zippo', '!!', '@', 'zIPPO', '112', '9', '2.3', '-3.8', '?']
 a.reverse()
 print(a)   # ['?', '-3.8', '2.3', '9', '112', 'zIPPO', '@', '!!', 'Zippo', 'Gigg', 'A', 'a', 'egg']

4.10 String str, tuple()

  • Strings can also be subscripted, sliced, used for loops, len(), in operator, not in operator

  • List elements are mutable, strings are immutable, and strings cannot reassign one of their characters.

  • Methods for mutating strings: slicing, concatenating.

  • Re-assign the entire list, the id (memory address) of the list is changed, if you don’t want to change, just overwrite, the memory address of the list remains unchanged, you can only delete the list value one by one through del, and then assign values ​​one by one through append .

  • Tuples are immutable. Values ​​cannot be modified, added, or deleted.

  • If the tuple has a value, add a comma (,) after it, otherwise it will be considered a string type.

 type(('hello',))    # 元组类型
 type('hello')       # 字符串类型

4.11 List and tuple types convert list(), tuple()

 print(list(('abc',)))   # abc
 print(list(('abc')))    # ['a', 'b', 'c']
 print(tuple(['a','b','c']))   # ('a', 'b', 'c')

4.12 Reference: copy(), deepcopy() functions

Use references when referring to values ​​of list or dictionary mutable data types .

For values ​​of immutable data types such as strings, integers, and tuples , variables hold the value itself.

  • Directly assign variable a to a new variable b, when b changes, a will not change.

  • Directly assign list a to a new list b, when an element of b changes, a will also change.

  • If you do not want the original list to change, use the slice assignment of a, or use the copy(), deepcopy() functions in the copy module

    • copy(): Deep copy the parent object (first-level directory), and the child object (second-level directory) is not copied, but still referenced.

    • deepcopy(): Both the parent object (first-level directory) and the child object (second-level directory) are copied.

 a1 = 10
 b1 = a1
 b1 = 99
 print(a1,b1)  # 10,99
 # -----------------------
 a2 = [1,2,3,4]
 b2 = a2
 b2[1] = 99
 print(a2,b2)  # [1,99,3,4]    [1,99,3,4]
 # -----------------------
 a3 = [1,2,3,4]
 b3 = a3[:]
 b3[1] = 99
 print(a3,b3)  # [1,2,3,4]    [1,99,3,4]
 # -----------------------
 a4 = {'name': 'Calhoun', 'age': 23}
 b4 = a4
 b4['age'] = 99
 print(a4, b4) # {'name': 'Calhoun', 'age': 99} {'name': 'Calhoun', 'age': 99}

copy(), deepcopy() function

 import copy
 dict1 = {'user': 'runoob', 'num': [1, 2, 3]}
 ​
 dict2 = dict1          # 浅拷贝: 引用对象
 dict3 = copy.copy(dict1)   # 浅拷贝:深拷贝父对象(一级目录),子对象(二级目录)不拷贝,子对象是引用
 dict4 = copy.deepcopy(dict1)  # 深拷贝
 ​
 # 修改 data 数据
 dict1['user'] = 'root'
 dict1['num'].remove(1)
 ​
 # 输出结果
 print('原字典:', dict1)
 print('赋值字典:', dict2)
 print('copy字典:', dict3)
 print('deepcopy字典:', dict4)
 ​
 """
 原字典: {'user': 'root', 'num': [2, 3]}
 赋值字典: {'user': 'root', 'num': [2, 3]}
 copy字典: {'user': 'runoob', 'num': [2, 3]}
 deepcopy字典: {'user': 'runoob', 'num': [1, 2, 3]}
 """

Chapter 5 Dictionaries dict{} and Structured Data

5.1 字典、dict.keys()、dict.values()、dict.items()

  • Key (key): The index of the dictionary, the dict.keys() method returns a value similar to a list, but it is not a real list and cannot be modified. Can be converted to a list with list().

  • Value (value): The value associated with the key of the dictionary. The dict.values() method returns a value similar to a list, but it is not a real list and cannot be modified. Can be converted to a list with list().

  • Key-value pairs (item): The dict.items() method returns a list-like value, but is not a real list and cannot be modified. Can be converted to a list with list().

 dict1 = {'user': 'runoob', 'num': [1, 2, 3]}
 a1 = dict1.keys()
 b1 = dict1.values()
 c1 = dict1.items()
 print(a1, b1, c1, end='\n', sep='\n')
 print(list(a1), list(b1), list(c1), end='\n', sep='\n')
 ​
 """
 dict_keys(['user', 'num'])
 dict_values(['runoob', [1, 2, 3]])
 dict_items([('user', 'runoob'), ('num', [1, 2, 3])])
 ​
 ['user', 'num']
 ['runoob', [1, 2, 3]]
 [('user', 'runoob'), ('num', [1, 2, 3])]
 """

The dictionary is not sorted, you can use in or not in to check whether the key exists in the dictionary. for dict in dict1 is shorthand for for dict in dict1.keys().

 dict1 = {'user': 'runoob', 'num': [1, 2, 3]}
 a21 = 'runoob' in dict1.items()
 a22 = 'runoob' in dict1.keys()
 a22_1 = 'runoob' in dict1
 a23 = 'runoob' in dict1.values()
 print(a21, a22, a22_1, a23)   # False False False True

5.2 get() method, setdefault() method

  • get(key to obtain value, alternate value returned if the key does not exist): If the key exists, return the value corresponding to the key, otherwise return the alternate value, the default alternate value can be set to 0.

  • setdefault(checked key, value set when the key does not exist): Set a default value for a key, but if the key exists, it will not be changed.

dict1 = {'user': 'runoob', 'num': [1, 2, 3]}
a1 = dict1.get('num',1) 
a2 = dict1.get('num1','None') 
print(a1,a2)    # [1, 2, 3] None
dict1.setdefault('Age',45)
print(dict1)    # {'user': 'runoob', 'num': [1, 2, 3], 'Age': 45}
dict1.setdefault('user','Bob')
print(dict1)    # {'user': 'runoob', 'num': [1, 2, 3], 'Age': 45}

setdefault() can be used to count the number of occurrences of each character in a string.

 msg = 'Hello,I\'m lijing.What is your name ?'
 count = {}
 for i in msg:
     count.setdefault(i, 0)
     count[i] = count[i] + 1
 print(count)
 ​
 """
 {'H': 1, 'e': 2, 'l': 3, 'o': 2, ',': 1, 'I': 1, "'": 1, 'm': 2, ' ': 5, 'i': 3, 'j': 1, 'n': 2, 'g': 1, '.': 1, 'W': 1, 'h': 1, 'a': 2, 't': 1, 's': 1, 'y': 1, 'u': 1, 'r': 1, '?': 1}
 """

5.3 pprint(), pformat() function

To use the pprint() and pformat() functions, you need to import the pprint module.

If you want to get a beautiful string displayed on the screen, use pprint.pformat(), print(pprint.pformat(count)) and pprint.pprint(count) in the following code are equivalent!

 import pprint
 msg = 'Hello,I\'m lijing.What is your name ?'
 count = {}
 for i in msg:
     count.setdefault(i, 0)
     count[i] = count[i] + 1
 f1 = pprint.pformat(count)
 pprint.pprint(count)
 ​
 """
 {' ': 5,
  "'": 1,
  ',': 1,
  '.': 1,
  '?': 1,
  'H': 1,
  'I': 1,
  'W': 1,
  'a': 2,
  'e': 2,
  'g': 1,
  'h': 1,
  'i': 3,
  'j': 1,
  'l': 3,
  'm': 2,
  'n': 2,
  'o': 2,
  'r': 1,
  's': 1,
  't': 1,
  'u': 1,
  'y': 1}
 """

Chapter 6 String Manipulation

6.1 Handling strings

  • Start and end the 'string' with double quotes so that the string can contain single quotes '.

  • Escape character \: You can use single quotes and double quotes in the string.

  • Raw string r: Make it a raw string by preceding the quotes with r, i.e. ignoring escape characters, print the \ symbol in the string.

  • Triple quotes: multi-line strings, which do not need to be escaped, and are often used for multi-line comments. Quotation marks, tabs, and newlines are all part of the string, and the code block indentation rules do not apply to multi-line strings.

  • #: Single-line comment.

6.2 String subscript, slice, in, not in operators

Similar to list.

6.3 Useful string methods

(1) upper()、lower()、isupper()、islower()

  • upper() : Returns a new string that converts the letters of the original string to uppercase, and the non-alphabetic characters remain unchanged. The original string is not changed!

  • lower() : Returns a new string that converts all letters of the original string to lowercase, leaving non-alphabetic characters unchanged. The original string is not changed!

  • isupper() : Returns a Boolean value, the string has at least one letter, and all letters are uppercase, the return value is true, otherwise it is false.

  • islower() : Returns a Boolean value, the string has at least one letter, and all letters are lowercase, the return value is true, otherwise it is false.

(2) isX()

  • isalpha(): Returns True if the string contains only letters and is not empty.

  • isalnum(): Returns True if the string contains only letters and numbers and is not empty.

  • isdecimal(): Returns True if the string contains only numeric characters and is not empty.

  • isspace(): Returns True if the string contains only spaces, tabs, and newlines, and is not empty.

  • istitle(): Returns True if the string contains only words starting with an uppercase letter followed by lowercase letters.

 a1, a2, a3, a4, a5 = 'Add', 'Add1234', '1234.5', ' \t', 'HueW'
 print(a1.isalpha(), a1.istitle())   # True True
 print(a2.isalnum(), a2.isdecimal())   # True False
 print(a3.isalpha(), a3.isdecimal())   # False False
 print(a4.isspace())   # True
 print(a5.istitle())   # False

(3) startswith()、endswith()

  • startswith(): returns True if the string starts with the calling string, otherwise returns False

  • endswith(): returns True if the string ends with the called string, otherwise returns False

 a1, a2= 'Add','HueW'
 print(a1.startswith('Ad'), a1.startswith('ad'))   # True False
 print(a2.endswith('eW'), a2.endswith('leW'))    # True False

(4) join()、split()

  • join(): Joins a list of strings into one string. 'Connector'.join(list of strings)

  • split(): Called on a string, returns a list of strings. The default is all null characters, including spaces, newlines (\n), tabs (\t), etc.

 a1 = '-'.join(['cats', 'rats', 'bats'])
 print(a1) # cats-rats-bats
 a2 = a1.split('-')
 print(a2) # ['cats', 'rats', 'bats']
 a3 = "MyHHHNameHHHIsHHHJing.".split('HHH')
 print(a3) # ['My', 'Name', 'Is', 'Jing.']
 msg = """ Dear,
 How have you been? I am fine .
 There is a container in the fridge that is labeled "Milk Experiment".
 ​
 Please do not drink it.
 Sincerely, Bob"""
 a4 = msg.split()    
 print(a4)
 """
 ['Dear,', 'How', 'have', 'you', 'been?', 'I', 'am', 'fine', '.', 'There', 'is', 'a', 'container', 'in', 'the', 'fridge', 'that', 'is', 'labeled', '"Milk', 'Experiment".', 'Please', 'do', 'not', 'drink', 'it.', 'Sincerely,', 'Bob']
 """

(5) Align text: rjust(), ljust(), center()

Aligns text by inserting filler characters.

  • rjust(): The string is right-aligned, and padding characters are filled on the left (default space). If the length of the string is greater than the specified length, it will not be filled and no error will be reported.

  • ljust(): The string is left aligned, and the padding characters are filled on the right

  • center(): The string is centered, and padding characters are added on both sides. First, a padding character is added to the right of the string, then to the left and then to the right, until the length reaches the specified length

 a1 = 'Hello'
 print(a1.rjust(10))
 print(a1.rjust(10, '*'))
 print(a1.rjust(4, '*'))
 print(a1.ljust(10, '*'))
 print(a1.center(10, '*'))
 """
      Hello
 *****Hello
 Hello
 Hello*****
 **Hello***
 """

(6) Delete blank characters: strip(), rstrip(), lstrip()

Removes whitespace characters (spaces, tabs, and newlines) from the left, right, or both sides of a string. Return a new string.

  • strip(): Without parameters, remove the leading or trailing blank characters.

  • rstrip(): Without parameters, delete the blank characters on the right

  • lstrip(): Without parameters, delete the left blank characters

  • String parameters can be entered, but the order of the strings is not important! As long as it contains these characters, it is case sensitive

 a1 = 'Hellol12345oolHe'
 print(a1.strip('eHl'))    # ol12345oo

(7) pyperclip module: computer clipboard

pyperclip is a third-party module, you need to install the package first:

 pip install pyperclip
  • copy(): Copy the content to the computer clipboard.

  • paste(): Paste the contents of the computer clipboard.

 import pyperclip
 a1 = '字符串'
 print(pyperclip.paste())   # 目前剪贴板的内容
 pyperclip.copy(a1)         # 字符串,在别的地方粘贴:字符串

Guess you like

Origin blog.csdn.net/yearx3/article/details/123419738