聪明办法学 Python 2nd Edition

发布时间 2023-12-01 16:26:53作者: 瑟兰迪尔·绿叶

聪明办法学 Python 2nd Edition

Chapter 5 循环 Loop

for 循环和循环范围

for 循环的特点

基于提供的范围,重复执行特定次数的操作

In [1]

def sumFromMToN(m, n):
    total = 0
    # 注意: range(x, y) 是左闭右开区间,包含 x,不包含 y
    for x in range(m, n+1):
        total += x
    return total

In [2]

sumFromMToN(5, 10)
45

In [3]

sumFromMToN(5, 10) == 5+6+7+8+9+10
True

range() 是个什么东西?

其实在这里,我们也可以不用循环来完成同样的任务

In [4]

def sumFromMToN(m, n):
    return sum(range(m, n+1))

In [5]

sumFromMToN(5, 10)
45

如果我们省略第一个参数会发生什么?

In [6]

def sumToN(n):
    total = 0
    # range 起始范围默认为 0
    for x in range(n+1):
        total += x
    return total

In [7]

sumToN(5)
15

那如果我们添加第三个参数呢?

In [8]

def sumEveryKthFromMToN(m, n, k):
    total = 0
    # 第三个参数为 “步长” step
    for x in range(m, n+1, k):
        total += x
    return total

In [9]

sumEveryKthFromMToN(5, 20, 7) == (5 + 12 + 19)
True

只对从 mn奇数求和

In [10]

# 我们也可以通过修改循环内部的代码来改变步长

def sumOfOddsFromMToN(m, n):
    total = 0
    for x in range(m, n+1):
        if x % 2 == 1:
            total += x
    return total

In [11]

sumOfOddsFromMToN(4, 10) == sumOfOddsFromMToN(5,9) == (5+7+9)
True

现在我们反着来试一下!

In [12]

# 我们将生成一个反向数字序列
# (仅供演示使用,代码实践中不建议这么做)

def sumOfOddsFromMToN(m, n):
    total = 0
    for x in range(n, m-1, -1):
        if x % 2 == 1:
            total += x
    return total

In [13]

sumOfOddsFromMToN(4, 10) == sumOfOddsFromMToN(5,9) == (5+7+9)
True

还有更多方法来解决这个问题

for 循环嵌套

In [14]

# 下面的代码将输出二维坐标

def printCoordinates(xMax, yMax):
    for x in range(1, xMax+1):
        for y in range(1, yMax+1):
            print(f"( {x} , {y} )  ", end="")
        print()

In [15]

printCoordinates(5, 5)
( 1 , 1 )  ( 1 , 2 )  ( 1 , 3 )  ( 1 , 4 )  ( 1 , 5 )  
( 2 , 1 )  ( 2 , 2 )  ( 2 , 3 )  ( 2 , 4 )  ( 2 , 5 )  
( 3 , 1 )  ( 3 , 2 )  ( 3 , 3 )  ( 3 , 4 )  ( 3 , 5 )  
( 4 , 1 )  ( 4 , 2 )  ( 4 , 3 )  ( 4 , 4 )  ( 4 , 5 )  
( 5 , 1 )  ( 5 , 2 )  ( 5 , 3 )  ( 5 , 4 )  ( 5 , 5 )  

In [16]

from IPython.display import IFrame
IFrame('https://pythontutor.com/visualize.html#code=%23%20%E4%B8%8B%E9%9D%A2%E7%9A%84%E4%BB%A3%E7%A0%81%E5%B0%86%E8%BE%93%E5%87%BA%E4%BA%8C%E7%BB%B4%E5%9D%90%E6%A0%87%0A%0Adef%20printCoordinates%28xMax,%20yMax%29%3A%0A%20%20%20%20for%20x%20in%20range%281,%20xMax%2B1%29%3A%0A%20%20%20%20%20%20%20%20for%20y%20in%20range%281,%20yMax%2B1%29%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20print%28f%22%28%20%7Bx%7D%20,%20%7By%7D%20%29%20%20%22,%20end%3D%22%22%29%0A%20%20%20%20%20%20%20%20print%28%29%0A%20%20%20%20%20%20%20%20%0AprintCoordinates%283,%203%29&cumulative=false&curInstr=0&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false', width=1300, height=800)
<IPython.lib.display.IFrame at 0x233782b5850>

如果换成 * 呢?

In [17]

def Stars(n, m):
    # 输出一个 n*m 的星型矩阵图
    for row in range(n):
        for col in range(m):
            print("*", end="")
        print()

In [18]

Stars(5, 5)
*****
*****
*****
*****
*****

换一种写法

In [19]

# be careful! 这些代码与之前的有什么不同?

def printMysteryStarShape(n):
    for row in range(n):
        print(row, end=" ")
        for col in range(row):
            print("*", end=" ")
        print()

In [20]

printMysteryStarShape(5)
0 
1 * 
2 * * 
3 * * * 
4 * * * * 

In [21]

from IPython.display import IFrame
IFrame('https://pythontutor.com/visualize.html#code=%23%20be%20careful!%20%E8%BF%99%E4%BA%9B%E4%BB%A3%E7%A0%81%E4%B8%8E%E4%B9%8B%E5%89%8D%E7%9A%84%E6%9C%89%E4%BB%80%E4%B9%88%E4%B8%8D%E5%90%8C%EF%BC%9F%0A%0Adef%20printMysteryStarShape%28n%29%3A%0A%20%20%20%20for%20row%20in%20range%28n%29%3A%0A%20%20%20%20%20%20%20%20print%28row,%20end%3D%22%20%22%29%0A%20%20%20%20%20%20%20%20for%20col%20in%20range%28row%29%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20print%28%22*%22,%20end%3D%22%20%22%29%0A%20%20%20%20%20%20%20%20print%28%29%0A%20%20%20%20%20%20%20%20%0AprintMysteryStarShape%285%29&cumulative=false&curInstr=0&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false', width=1300, height=800)
<IPython.lib.display.IFrame at 0x233781b3a60>

while 循环

嘿!

当你不知道循环什么时候停下来的时候,为什么不试试 while

找出一个数最左边的那一位的数值(123451

In [22]

# 我不知道它什么时候停下来

def leftmostDigit(n):
    n = abs(n)
    while n >= 10:
        n = n//10
    return n 

In [23]

leftmostDigit(46535248)
4

举个例子:依次找出 n 个 4 或者 7 的整数倍非负整数

In [24]

def isMultipleOf4or7(x):
    return ((x % 4) == 0) or ((x % 7) == 0)

def nthMultipleOf4or7(n):
    found = 0
    guess = -1
    while found <= n:
        guess += 1
        if isMultipleOf4or7(guess):
            found += 1
    return guess

In [25]

print("4 或 7 的倍数: ", end="")
for n in range(15):
    print(nthMultipleOf4or7(n), end=" ")
4 或 7 的倍数: 0 4 7 8 12 14 16 20 21 24 28 32 35 36 40 

Bad Style:在知道循环范围的情况下使用 while

In [26]

def sumToN(n):
    # 尽管它能正确运行,但是这是非常不推荐的做法!
    # 应该使用 for 循环而不是 while 循环
    total = 0
    counter = 1
    while counter <= n:
        total += counter
        counter += 1
    return total

In [27]

sumToN(5) == 1+2+3+4+5
True

break 与 continue 语句

In [28]

for n in range(200):
    if n % 3 == 0:
        continue # 跳过这次循环
    elif n == 8:
        break # 跳出当前整个循环
    else:
        pass # 啥也不做,占位符(不会被运行)
    print(n, end=" ")
1 2 4 5 7 

假·死循环

与环境交互后,在特定条件下终止的循环

In [29]

# 不需要看懂这些代码,关注演示的过程

def readUntilDone():
    linesEntered = 0
    while True:
        response = input("输入一个字符串(输入 done 则退出): ")
        if response == "done":
            break
        print("你输入了: ", response)
        linesEntered += 1
    print("Bye!")
    return linesEntered

In [30]

linesEntered = readUntilDone()
print("你输入了", linesEntered, "行 (不包括 'done').")
你输入了:  learn
你输入了:  python
你输入了:  the
你输入了:  smart
你输入了:  way
Bye!
你输入了 5 行 (不包括 'done').

isPrime

判断一个数是不是质数

In [31]

# 不是最快的写法,但最容易理解

def isPrime(n):
    if n < 2:
        return False
    for factor in range(2,n):
        if n % factor == 0:
            return False
    return True

In [32]

for n in range(100):
    if isPrime(n):
        print(n, end=" ")
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 

faster IsPrime:

In [33]

# 快了一点

def fasterIsPrime(n):
    if n < 2:
        return False
    if n == 2:
        return True
    if n % 2 == 0:
        return False
    maxFactor = round(n**0.5)
    for factor in range(3, maxFactor+1, 2):
        if n % factor == 0:
            return False
    return True

In [34]

for n in range(100):
    if fasterIsPrime(n):
        print(n, end=" ")
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 

真的快了?

In [35]

# 验证他它俩结果是一样的
for n in range(100):
    assert(isPrime(n) == fasterIsPrime(n))
print("两种解法的结果一致")
两种解法的结果一致

In [39]

import time

bigPrime = 102030407
print("Timing isPrime(",bigPrime,")", end=" ")

# isPrime
time0 = time.time()
print(", returns ", isPrime(bigPrime), end=" ")

time1 = time.time()
print(", time = ",(time1-time0)*1000,"ms\n")

# fasterIsPrime
print("Timing fasterIsPrime(",bigPrime,")", end=" ")
time0 = time.time()

print(", returns ", fasterIsPrime(bigPrime), end=" ")
time1 = time.time()

# result
print(", time = ",(time1-time0)*1000,"ms")
Timing isPrime( 102030407 ) , returns  True , time =  4708.568811416626 ms

Timing fasterIsPrime( 102030407 ) , returns  True , time =  0.4515647888183594 ms

nth Prime

依次找出第 n 位质数

In [37]

def nthPrime(n):
    found = 0
    guess = 0
    while found <= n:
        guess += 1
        if fasterIsPrime(guess):
            found += 1
    return guess

In [38]

for n in range(10):
    print(n, nthPrime(n))
print("Done!")
0 2
1 3
2 5
3 7
4 11
5 13
6 17
7 19
8 23
9 29
Done!

总结

  • For 循环用于指定范围的重复操作。

  • range() 可以生成一个数字范围。

  • 在不知道循环什么时间停止的时候,应该试试 While 循环。

  • 循环同样也是可以嵌套的。

  • 巧妙地使用 breakcontinue 语句。

  • 合理的剪枝,缩小搜索范围/循环范围,可以大幅提高程序运行效率。

  • 聪明办法学 Python 2nd Edition

    Chapter 6 字符串 Strings

    字符串文字

    四种引号

    引号的作用就是将文字包裹起来,告诉 Python "这是个字符串!"

    单引号 ' 和双引号 " 是最常见的两种字符字符串引号

    In [1]

    print('单引号')
    print("双引号")
    单引号
    双引号
    

    三个引号的情况不太常见,但是它在一些场合有特定的作用(如函数文档 doc-strings)

    In [2]

    print('''三个单引号''')
    print("""三个双引号""")
    三个单引号
    三个双引号
    

    我们为什么需要两种不同的引号?

    In [3]

    # 为了写出这样的句子
    print("聪明办法学 Python 第二版的课程简称是 'P2S'")
    聪明办法学 Python 第二版的课程简称是 'P2S'
    

    如果我们偏要只用一种引号呢?

    In [4]

    # 这会导致语法错误,Python 无法正确判断一个字符串的终止位置
    print("聪明办法学 Python 第二版的课程简称是 "P2S"")
    

    Cell In [4], line 2 print("聪明办法学 Python 第二版的课程简称是 "P2S"") ^ SyntaxError****: invalid syntax

    字符串中的换行符号

    前面有反斜杠 \ 的字符,叫做转义序列

    比如 \n 代表换行,尽管它看起来像两个字符,但是 Python 依然把它视为一个特殊的字符

    In [5]

    # 这两个 print() 在做同样的事情 
    print("Data\nwhale")  # \n 是一个单独的换行符号
    Data
    whale
    

    In [6]

    print("""Data
    whale""")
    Data
    whale
    

    In [7]

    print("""你可以在字符串后面使用 反斜杠 `\`  来排除后面的换行。\
    比如这里是第二行文字,但是你会看到它会紧跟在上一行句号后面。\
    这种做法在 CIL 里面经常使用(多个 Flag 并排保持美观),\
    但是在编程中的应用比较少。\
    """)
    你可以在字符串后面使用 反斜杠 `\`  来排除后面的换行。比如这里是第二行文字,但是你会看到它会紧跟在上一行句号后面。这种做法在 CIL 里面经常使用(多个 Flag 并排保持美观),但是在编程中的应用比较少。
    

    In [8]

    print("""你可以在字符串后面使用 反斜杠 `\`  来排除后面的换行。
    比如这里是第二行文字,但是你会看到它会紧跟在上一行句号后面。
    这种做法在 CIL 里面经常使用(多个 Flag 并排保持美观),
    但是在编程中的应用比较少。
    """)
    你可以在字符串后面使用 反斜杠 `\`  来排除后面的换行。
    比如这里是第二行文字,但是你会看到它会紧跟在上一行句号后面。
    这种做法在 CIL 里面经常使用(多个 Flag 并排保持美观),
    但是在编程中的应用比较少。
    

    其他的转义序列

    In [9]

    print("双引号:\"")
    双引号:"
    

    In [10]

    print("反斜线:\\")
    反斜线:\
    

    In [11]

    print("换\n行")
    换
    行
    

    In [12]

    print("这个是\t制\t表\t符\n也叫\t跳\t格\t键")
    这个是	制	表	符
    也叫	跳	格	键
    

    转义序列只作为一个字符存在

    In [13]

    s = "D\\a\"t\ta"
    print("s =", s)
    print("\ns 的长度为:", len(s))
    s = D\a"t	a
    
    s 的长度为: 7
    

    repr() vs. print()

    我们现在有两个字符串

    In [14]

    s1 = "Data\tWhale"
    s2 = "Data        Whale"
    

    它俩看起来似乎是一样的

    In [15]

    print("s1:", s1)
    print("s2:", s2)
    s1: Data	Whale
    s2: Data        Whale
    

    但是它们真的一样吗?

    In [16]

    s1 == s2
    False
    

    如来佛合掌道:“观音尊者,你看那两个行者,谁是真假?”

    “谛听,汝之神通,能分辨出谁是真身,可为我说之。”

    In [17]

    print(repr(s1))
    print(repr(s2))
    'Data\tWhale'
    'Data        Whale'
    

    In [18]

    hack_text = "密码应当大于 8 个字符,小于 16 个字符,包含大写字母、小写字母、数字和特殊符号\t\t\t\t\t\t\t\t\t\t\t\t\t"
    

    In [19]

    print(hack_text)
    密码应当大于 8 个字符,小于 16 个字符,包含大写字母、小写字母、数字和特殊符号													
    

    In [20]

    print(repr(hack_text))
    '密码应当大于 8 个字符,小于 16 个字符,包含大写字母、小写字母、数字和特殊符号\t\t\t\t\t\t\t\t\t\t\t\t\t'
    

    多行字符串作为注释

    In [21]

    """
    Python 本身是没有多行注释的,
    但是你可以用多行字符串实现同样的操作,
    还记得我们之前学过的“表达式“吗?
    它的原理就是 Python 会运行它,
    但是马上扔掉!(垃圾回收机制)
    """
    print("Amazing!")
    Amazing!
    

    一些字符串常量

    In [22]

    import string
    print(string.ascii_letters)
    abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
    

    In [23]

    print(string.ascii_lowercase)
    abcdefghijklmnopqrstuvwxyz
    

    In [24]

    print(string.ascii_uppercase) 
    ABCDEFGHIJKLMNOPQRSTUVWXYZ
    

    In [25]

    print(string.digits)
    0123456789
    

    In [26]

    print(string.punctuation) # < = >
    !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
    

    In [27]

    print(string.printable)
    0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ 	
    

    In [28]

    print(string.whitespace)
    
    

    In [29]

    print(repr(string.whitespace))
    ' \t\n\r\x0b\x0c'
    

    一些字符串的运算

    字符串的加减

    In [30]

    print("abc" + "def")
    print("abc" * 3)
    abcdef
    abcabcabc
    

    In [31]

    print("abc" + 3)
    

    ---------------------------------------------------------------------------****TypeError Traceback (most recent call last)Cell In [31], line 1 ----> 1 print("abc" + 3) TypeError: can only concatenate str (not "int") to str

    in 运算(超级好用!)

    In [32]

    print("ring" in "strings") # True
    print("wow" in "amazing!") # False
    print("Yes" in "yes!") # False
    print("" in "No way!") # True
    print("聪明" in "聪明办法学 Python") # True
    True
    False
    False
    True
    True
    

    字符串索引和切片

    单个字符索引

    索引可以让我们在特定位置找到一个字符

    In [33]

    s = "Datawhale"
    print(s)
    print(s[0])
    print(s[1])
    print(s[2])
    print(s[3])
    Datawhale
    D
    a
    t
    a
    

    In [34]

    len(s)
    9
    

    In [35]

    print(s[len(s)-1])
    e
    

    In [36]

    print(s[len(s)])
    

    ---------------------------------------------------------------------------****IndexError Traceback (most recent call last)Cell In [36], line 1 ----> 1 print(s[len(s)]) IndexError: string index out of range

    负数索引

    In [37]

    print(s)
    print(s[-5])
    print(s[-4])
    print(s[-3])
    print(s[-2])
    print(s[-1])
    Datawhale
    w
    h
    a
    l
    e
    

    用切片来获取字符串的一部分

    In [38]

    print(s[0:4])
    print(s[4:9])
    Data
    whale
    

    In [39]

    print(s[0:2])
    print(s[2:4])
    print(s[5:7])
    print(s[7:9])
    Da
    ta
    ha
    le
    

    切片的默认参数

    In [85]

    print(s[:4])
    print(s[4:])
    print(s[:])
    Data
    whale
    Datawhale
    

    切片的第三个参数 step

    In [86]

    print(s[:9:3])
    print(s[1:4:2])
    Daa
    aa
    

    翻转字符串

    In [87]

    # 可以,但是不优雅
    print(s[::-1])
    elahwataD
    

    In [88]

    # 也可以,但是还是不够优雅
    print("".join(reversed(s)))
    elahwataD
    

    In [89]

    # 实在是太优雅辣
    def reverseString(s):
        return s[::-1]
    
    print(reverseString(s))
    elahwataD
    

    字符串的循环

    用索引的 for 循环

    In [90]

    for i in range(len(s)):
        print(i, s[i])
    0 D
    1 a
    2 t
    3 a
    4 w
    5 h
    6 a
    7 l
    8 e
    

    其实也可以不用索引(超级好用的 in

    In [91]

    for c in s:
        print(c)
    D
    a
    t
    a
    w
    h
    a
    l
    e
    

    也可以使用 enumerate() 获得元素的序号

    In [92]

    for idx, c in enumerate(s):
        print(idx, c)
    0 D
    1 a
    2 t
    3 a
    4 w
    5 h
    6 a
    7 l
    8 e
    

    zip(a, b) 可以在一次循环中,分别从 ab 里同时取出一个元素

    In [93]

    for a, b in zip(s, reverseString(s)):
        print(a, b)
    D e
    a l
    t a
    a h
    w w
    h a
    a t
    l a
    e D
    

    split() 来循环

    In [94]

    # class_name.split() 本身会产生一个新的叫做“列表”的东西,但是它不存储任何内容
    
    class_name = "learn python the smart way 2nd edition"
    for word in class_name.split():
        print(word)
    learn
    python
    the
    smart
    way
    2nd
    edition
    

    splitlines() 来循环

    In [95]

    # 跟上面一样,class_info.splitlines() 也会产生一个列表,但不存储任何内容
    
    class_info = """\
    聪明办法学 Python 第二版是 Datawhale 基于第一版教程的一次大幅更新。我们尝试在教程中融入更多计算机科学与人工智能相关的内容,制作“面向人工智能的 Python 专项教程”。
    
    我们的课程简称为 P2S,有两个含义:
    
    Learn Python The Smart Way V2,“聪明办法学 Python 第二版”的缩写。
    Prepare To Be Smart, 我们希望同学们学习这个教程后能学习到聪明的办法,从容的迈入人工智能的后续学习。
    """
    for line in class_info.splitlines():
        if (line.startswith("Prepare To Be Smart")):
            print(line)
    Prepare To Be Smart, 我们希望同学们学习这个教程后能学习到聪明的办法,从容的迈入人工智能的后续学习。
    

    例子:回文判断

    如果一个句子正着读、反着读都是一样的,那它就叫做“回文”

    In [96]

    def isPalindrome1(s):
        return (s == reverseString(s))
    

    In [97]

    def isPalindrome2(s):
        for i in range(len(s)):
            if (s[i] != s[len(s)-1-i]):
                return False
        return True
    

    In [98]

    def isPalindrome3(s):
        for i in range(len(s)):
            if (s[i] != s[-1-i]):
                return False
        return True
    

    In [99]

    def isPalindrome4(s):
        while (len(s) > 1):
            if (s[0] != s[-1]):
                return False
            s = s[1:-1]
        return True
    

    In [100]

    print(isPalindrome1("abcba"), isPalindrome1("abca"))
    print(isPalindrome2("abcba"), isPalindrome2("abca"))
    print(isPalindrome3("abcba"), isPalindrome3("abca"))
    print(isPalindrome4("abcba"), isPalindrome4("abca"))
    True False
    True False
    True False
    True False
    

    一些跟字符串相关的内置函数

    str()` 和 `len()
    

    In [43]

    name = input("输入你的名字: ")
    print("Hi, " + name + ", 你的名字有 " + str(len(name)) + " 个字!")
    输入你的名字: Datawhale
    Hi, Datawhale, 你的名字有 9 个字!
    chr()` 和 `ord()
    

    In [102]

    print(ord("A"))
    65
    

    In [103]

    print(chr(65))
    A
    

    In [104]

    print(
        chr(
            ord("A") + 1
        )
    )
    B
    

    In [105]

    print(chr(ord("A") + ord(" ")))
    a
    

    In [44]

    # 它可以正常运行,但是我们不推荐你使用这个方法
    s = "(3**2 + 4**2)**0.5"
    print(eval(s))
    5.0
    

    In [2]

    def 电脑当场爆炸():
        from rich.progress import (
            Progress, 
            TextColumn, 
            BarColumn, 
            TimeRemainingColumn)
        import time
        from rich.markdown import Markdown
        from rich import print as rprint
        from rich.panel import Panel
    
    
        with Progress(TextColumn("[progress.description]{task.description}"),
                    BarColumn(),
                    TimeRemainingColumn()) as progress:
            epoch_tqdm = progress.add_task(description="爆炸倒计时!", total=100)
            for ep in range(100):
                time.sleep(0.1)
                progress.advance(epoch_tqdm, advance=1)
    
        rprint(Panel.fit("[red]Boom! R.I.P"))
    

    In [45]

    s = "电脑当场爆炸()"
    eval(s) # 如果这是一串让电脑爆炸的恶意代码,那会发生什么
    爆炸倒计时! [38;2;249;38;114m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━[0m[38;2;249;38;114m╸[0m [36m0:00:01[0m
    ╭─────────────╮
    │ [31mBoom! R.I.P[0m │
    ╰─────────────╯
    

    In [46]

    # 推荐使用 ast.literal_eval()
    
    import ast
    s_safe = "['p', 2, 's']"
    s_safe_result = ast.literal_eval(s_safe)
    print(s_safe_result)
    print(type(s_safe_result))
    ['p', 2, 's']
    <class 'list'>
    

    一些字符串方法

    In [47]

    def p(test):
        print("True     " if test else "False    ", end="")
    def printRow(s):
        print(" " + s + "  ", end="")
        p(s.isalnum())
        p(s.isalpha())
        p(s.isdigit())
        p(s.islower())
        p(s.isspace())
        p(s.isupper())
        print()
    def printTable():
        print("  s   isalnum  isalpha  isdigit  islower  isspace  isupper")
        for s in "ABCD,ABcd,abcd,ab12,1234,    ,AB?!".split(","):
            printRow(s)
    printTable()
      s   isalnum  isalpha  isdigit  islower  isspace  isupper
     ABCD  True     True     False    False    False    True     
     ABcd  True     True     False    False    False    False    
     abcd  True     True     False    True     False    False    
     ab12  True     False    False    True     False    False    
     1234  True     False    True     False    False    False    
           False    False    False    False    True     False    
     AB?!  False    False    False    False    False    True     
    

    In [48]

    print("YYDS YYSY XSWL DDDD".lower())
    print("fbi! open the door!!!".upper())
    yyds yysy xswl dddd
    FBI! OPEN THE DOOR!!!
    

    img

    In [112]

    print("   strip() 可以将字符串首尾的空格删除    ".strip())
    strip() 可以将字符串首尾的空格删除
    

    In [113]

    print("聪明办法学 Python".replace("Python", "C"))
    print("Hugging LLM, Hugging Future".replace("LLM", "SD", 1)) # count = 1
    聪明办法学 C
    Hugging SD, Hugging Future
    

    In [114]

    s = "聪明办法学Python, 就找 Datawhale"
    t = s.replace("聪明办法", "")
    print(t)
    学Python, 就找 Datawhale
    

    In [115]

    print("This is a history test".count("is"))
    print("This IS a history test".count("is"))
    3
    2
    

    In [116]

    print("Dogs and cats!".startswith("Do"))
    print("Dogs and cats!".startswith("Don't"))
    True
    False
    

    In [117]

    print("Dogs and cats!".endswith("!"))
    print("Dogs and cats!".endswith("rats!"))
    True
    False
    

    In [118]

    print("Dogs and cats!".find("and"))
    print("Dogs and cats!".find("or"))
    5
    -1
    

    In [119]

    print("Dogs and cats!".index("and"))
    print("Dogs and cats!".index("or"))
    5
    

    ---------------------------------------------------------------------------****ValueError Traceback (most recent call last)c:\Coding\Datawhale\Python_Tutorial\learn-python-the-smart-way-v2\slides\chapter_6-Strings.ipynb Cell 112 line 2 1 print("Dogs and cats!".index("and")) ----> 2 print("Dogs and cats!".index("or")) ValueError: substring not found

    f-string 格式化字符串

    In [120]

    x = 42
    y = 99
    
    print(f'你知道 {x} + {y} 是 {x+y} 吗?')
    你知道 42 + 99 是 141 吗?
    

    其他格式化字符串的方法

    如果要格式化字符串的话,f-string 是个很棒的方法,Python 还有其他方法去格式化字符串:

    • % 操作
    • format() 方法

    参考资料:

    字符串是不可变的

    In [121]

    s = "Datawhale"
    s[3] = "e"  # Datewhale
    

    ---------------------------------------------------------------------------****TypeError Traceback (most recent call last)c:\Coding\Datawhale\Python_Tutorial\learn-python-the-smart-way-v2\slides\chapter_6-Strings.ipynb Cell 118 line 2 1 s = "Datawhale" ----> 2 s[3] = "e" TypeError: 'str' object does not support item assignment

    你必须创建一个新的字符串

    In [122]

    s = s[:3] + "e" + s[4:]
    print(s)
    Datewhale
    

    字符串和别名

    字符串是不可变的,所以它的别名也是不可变的

    In [123]

    s = 'Data'  # s 引用了字符串 “Data”
    t = s      # t 只是 “Data” 的一个只读别名
    s += 'whale'
    print(s)
    print(t)
    Datawhale
    Data
    

    In [124]

    t[3] = "e"
    

    ---------------------------------------------------------------------------****TypeError Traceback (most recent call last)c:\Coding\Datawhale\Python_Tutorial\learn-python-the-smart-way-v2\slides\chapter_6-Strings.ipynb Cell 124 line 1 ----> 1 t[3] = "e" TypeError: 'str' object does not support item assignment

    基础文件操作

    Open() 函数

    Python open() 函数用于打开一个文件,并返回文件对象,在对文件进行处理过程都需要使用到这个函数。

    open(file, mode) 函数主要有 filemode 两个参数,其中 file 为需要读写文件的路径。mode 为读取文件时的模式,常用的模式有以下几个:

    • r:以字符串的形式读取文件。
    • rb:以二进制的形式读取文件。
    • w:写入文件。
    • a:追加写入文件。

    不同模式下返回的文件对象功能也会不同。

    In [125]

    file = open("chap6_demo.txt", "w")
    dw_text = "Datawhale"
    file.write(dw_text)
    file.close()
    

    In [126]

    file = open('chap6_demo.txt', 'r')
    print(type(file))
    <class '_io.TextIOWrapper'>
    

    文件对象

    open 函数会返回一个 文件对象。在进行文件操作前,我们首先需要了解文件对象提供了哪些常用的方法:

    • close( ): 关闭文件

    • r

      rb

      模式下:

      • read(): 读取整个文件
      • readline(): 读取文件的一行
      • readlines(): 读取文件的所有行
    • w

      a

      模式下:

      • write():
      • writelines():

    下面我们通过实例学习这几种方法:

    In [127]

    ## 通过 read 方法读取整个文件
    content = file.read()
    print(content)
    Datawhale
    

    In [128]

    ## 通过 readline() 读取文件的一行
    content = file.readline()
    print(content)
    

    代码竟然什么也没输出,这是为什么?

    In [129]

    ## 关闭之前打开的 chap6_demo.txt 文件
    file.close()
    ## 重新打开
    file = open('chap6_demo.txt', 'r')
    content = file.readline()
    print(content)
    Datawhale
    

    注意每次操作结束后,及时通过 close( ) 方法关闭文件

    In [130]

    ## 以 w 模式打开文件chap6_demo.txt
    file = open('chap6_demo.txt', 'w')
    ## 创建需要写入的字符串变量 在字符串中 \n 代表换行(也就是回车)
    content = 'Data\nwhale\n'
    ## 写入到 chap6_demo.txt 文件中
    file.write(content)
    ## 关闭文件对象
    file.close()
    

    w 模式会覆盖之前的文件。如果你想在文件后面追加内容,可以使用 a 模式操作。

    In [131]

    ## 以 w 模式打开文件chap6_demo.txt
    file = open('chap6_demo.txt', 'w')
    ## 创建需要追加的字符串变量
    content = 'Hello smart way!!!'
    ## 写入到 chap6_demo.txt 文件中
    file.write(content)
    ## 关闭文件对象
    file.close()
    

    with 语句

    我不想写 close() 啦!

    In [132]

    import this
    The Zen of Python, by Tim Peters
    
    Beautiful is better than ugly.
    Explicit is better than implicit.
    Simple is better than complex.
    Complex is better than complicated.
    Flat is better than nested.
    Sparse is better than dense.
    Readability counts.
    Special cases aren't special enough to break the rules.
    Although practicality beats purity.
    Errors should never pass silently.
    Unless explicitly silenced.
    In the face of ambiguity, refuse the temptation to guess.
    There should be one-- and preferably only one --obvious way to do it.
    Although that way may not be obvious at first unless you're Dutch.
    Now is better than never.
    Although never is often better than *right* now.
    If the implementation is hard to explain, it's a bad idea.
    If the implementation is easy to explain, it may be a good idea.
    Namespaces are one honking great idea -- let's do more of those!
    

    In [133]

    Caesar_cipher = """s = \"\"\"Gur Mra bs Clguba, ol Gvz Crgref
    
    Ornhgvshy vf orggre guna htyl.
    Rkcyvpvg vf orggre guna vzcyvpvg.
    Fvzcyr vf orggre guna pbzcyrk.
    Pbzcyrk vf orggre guna pbzcyvpngrq.
    Syng vf orggre guna arfgrq.
    Fcnefr vf orggre guna qrafr.
    Ernqnovyvgl pbhagf.
    Fcrpvny pnfrf nera'g fcrpvny rabhtu gb oernx gur ehyrf.
    Nygubhtu cenpgvpnyvgl orngf chevgl.
    Reebef fubhyq arire cnff fvyragyl.
    Hayrff rkcyvpvgyl fvyraprq.
    Va gur snpr bs nzovthvgl, ershfr gur grzcgngvba gb thrff.
    Gurer fubhyq or bar-- naq cersrenoyl bayl bar --boivbhf jnl gb qb vg.
    Nygubhtu gung jnl znl abg or boivbhf ng svefg hayrff lbh'er Qhgpu.
    Abj vf orggre guna arire.
    Nygubhtu arire vf bsgra orggre guna *evtug* abj.
    Vs gur vzcyrzragngvba vf uneq gb rkcynva, vg'f n onq vqrn.
    Vs gur vzcyrzragngvba vf rnfl gb rkcynva, vg znl or n tbbq vqrn.
    Anzrfcnprf ner bar ubaxvat terng vqrn -- yrg'f qb zber bs gubfr!\"\"\"
    
    d = {}
    for c in (65, 97):
        for i in range(26):
            d[chr(i+c)] = chr((i+13) % 26 + c)
    
    print("".join([d.get(c, c) for c in s]))
    """
    

    In [134]

    with open("ZenOfPy.py", "w", encoding="utf-8") as file:
        file.write(Caesar_cipher)
        print(len(Caesar_cipher))
    1003
    

    In [135]

    import ZenOfPy
    The Zen of Python, by Tim Peters
    
    Beautiful is better than ugly.
    Explicit is better than implicit.
    Simple is better than complex.
    Complex is better than complicated.
    Flat is better than nested.
    Sparse is better than dense.
    Readability counts.
    Special cases aren't special enough to break the rules.
    Although practicality beats purity.
    Errors should never pass silently.
    Unless explicitly silenced.
    In the face of ambiguity, refuse the temptation to guess.
    There should be one-- and preferably only one --obvious way to do it.
    Although that way may not be obvious at first unless you're Dutch.
    Now is better than never.
    Although never is often better than *right* now.
    If the implementation is hard to explain, it's a bad idea.
    If the implementation is easy to explain, it may be a good idea.
    Namespaces are one honking great idea -- let's do more of those!
    

    总结

    • 单引号与双引号要适时出现,多行文本用三引号。
    • 字符串中可以包含转义序列。
    • repr() 能够显示出更多的信息。
    • 字符串本身包含许多内置方法,in 是一个特别好用的玩意。
    • 字符串是不可变的常量。
    • 文件操作推荐使用 with open("xxx") as yyy,这样就不用写 f.close() 啦。

    首先在这里恭喜各位同学完成了《聪明办法学 Python 第二版》基础部分的全部学习内容! 在这 6 章的学习中希望你可以体会到本教程简洁明快的风格,这种风格与 Python 本身的代码设计风格是一致的。在 Tim Peters 编写的 “Python 之禅” 中的核心指导原则就是 “Simple is better than complex”。

    纵观历史,你会看到苹果创始人史蒂夫·乔布斯对 Less is More 的追求,看到无印良品“删繁就简,去其浮华”的核心设计理念,看到山下英子在《断舍离》中对生活做减法的观点,甚至看到苏东坡“竹杖芒鞋轻胜马,一蓑烟雨任平生”的人生态度。你会发现极简主义不只存在于 Python 编程中,它本就是这个世界优雅的一条运行法则。

    原文链接

    $\textcolor{red}{本文部分引用自网络}$

    $\textcolor{red}{文章架构来源于课程ppt(免责声明)}$

    课程ppt链接