首页 > 其他分享 >循环,字符串,基础文件操作的用法

循环,字符串,基础文件操作的用法

时间:2023-12-02 18:45:07浏览次数:39  
标签:文件 False 用法 print 循环 file 字符串 True

Task06:循环Loop and 字符串string

循环Loop

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

range(m,n)左开右闭从m遍历到n-1

sumFromMToN(5, 10)
45

range() 是个什么东西?

不用循环来完成同样的任务

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

1,对于两个参数,就是一个左闭右开的遍历区间

2,对于一个参数,左区间默认为零

3,对于三个参数,前面两个是左闭右开的遍历区间,而第三个是步长

eg:

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

True

for 的嵌套

# 下面的代码将输出二维坐标
def printCoordinates(xMax, yMax):
    for x in range(1, xMax+1):
        for y in range(1, yMax+1):
            print(f"( {x} , {y} )  ", end="")
        print()
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 ) 

//

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

//

# be careful! 这些代码与之前的有什么不同?
def printMysteryStarShape(n):
    for row in range(n):
        print(row, end=" ")
        for col in range(row):
            print("*", end=" ")
        print()
printMysteryStarShape(5)
0 
1 * 
2 * * 
3 * * * 
4 * * * * 

row是行号,从零开始

while循环
# 我不知道它什么时候停下来
def leftmostDigit(n):
    n = abs(n)
    while n >= 10:
        n = n//10
    return n 
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
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 
break and continue

与c语言一样,continue是跳过本次循环,break是终止这一层循环

死循环

while True:

//

for循环耗时很多,

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

第一个找质数函数与第二个找指数函数结果相同,而第一个是遍历到n-1

第二个遍历到n0.5**,时间就会快很多

//

找出第n位质数

ef nthPrime(n):
    found = 0
    guess = 0
    while found <= n:
        guess += 1
        if fasterIsPrime(guess):
            found += 1
    return guess
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!

字符串string

四种引号

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

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

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

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

跟文学上的用法差不多

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

换行符号

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

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

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

下面这个例子可以秒杀马里奥,想要换行输出就需要用这种三个引号

排除换行

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

转义字符

print("双引号:\"")
双引号:"
print("反斜线:\\")
反斜线:\
print("换\n行")
换
行
print("这个是\t制\t表\t符\n也叫\t跳\t格\t键")
这个是	制	表	符
也叫	跳	格	键

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

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

s 的长度为: 7

repr() vs. print()

s1 = "Data\tWhale"
s2 = "Data        Whale"
print("s1:", s1)
print("s2:", s2)
s1: Data	Whale
s2: Data    Whale

输出虽然是一样的,但是他们不是相等的

s1 == s2

False

repr可以识别整个字符串的内容

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

一些字符串常量

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








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

字符串的加减

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

最后一行会报错因为3不是字符串

in运算

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

“A" in "B"

B中有字串和A相同就返回True,大小写敏感

字符串索引和切片

单个字符索引

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

s = "Datawhale"
print(s)
print(s[0])
print(s[1])
print(s[2])
print(s[3])
Datawhale
D
a
t
a
len(s)
9
print(s[len(s)-1])
e
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

负数索引

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

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

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

切片的默认参数

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

切片的第三个参数 step

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

翻转字符串

# 可以,但是不优雅
print(s[::-1])
elahwataD:
# 也可以,但是还是不够优雅
print("".join(reversed(s)))
elahwataD
# 实在是太优雅辣
def reverseString(s):
    return s[::-1]

print(reverseString(s))
elahwataD

字符串的循环

用索引的 for 循环

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

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

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

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 里同时取出一个元素

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() 来循环

# 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() 来循环

# 跟上面一样,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, 我们希望同学们学习这个教程后能学习到聪明的办法,从容的迈入人工智能的后续学习。

chr()and ord()

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

一些字符串方法

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     
print("YYDS YYSY XSWL DDDD".lower())
print("fbi! open the door!!!".upper())
yyds yysy xswl dddd
FBI! OPEN THE DOOR!!!
print("   strip() 可以将字符串首尾的空格删除    ".strip())
strip() 可以将字符串首尾的空格删除
print("聪明办法学 Python".replace("Python", "C"))
print("Hugging LLM, Hugging Future".replace("LLM", "SD", 1)) # count = 1
聪明办法学 C
Hugging SD, Hugging Future
s = "聪明办法学Python, 就找 Datawhale"
t = s.replace("聪明办法", "")
print(t)
学Python, 就找 Datawhale
print("This is a history test".count("is"))
print("This IS a history test".count("is"))
3
2

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

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

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

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

字符串和别名

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

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

基础文件操作

Open() 函数

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

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

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

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

file = open("chap6_demo.txt", "w")
dw_text = "Datawhale"
file.write(dw_text)
file.close()
file = open('chap6_demo.txt', 'r')
print(type(file))
<class '_io.TextIOWrapper'>

文件对象

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

  • close( ): 关闭文件
  • 在r与rb模式下:
    • read(): 读取整个文件
    • readline(): 读取文件的一行
    • readlines(): 读取文件的所有行
  • 在w与a模式下:
    • write():
    • writelines():

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

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

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

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

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

## 以 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 模式操作。

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

文件操作推荐使用 with open("xxx") as yyy,这样就不用写 f.close()

Task06:循环Loop and 字符串string

循环Loop

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

range(m,n)左开右闭从m遍历到n-1

sumFromMToN(5, 10)
45

range() 是个什么东西?

不用循环来完成同样的任务

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

1,对于两个参数,就是一个左闭右开的遍历区间

2,对于一个参数,左区间默认为零

3,对于三个参数,前面两个是左闭右开的遍历区间,而第三个是步长

eg:

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

True

for 的嵌套

# 下面的代码将输出二维坐标
def printCoordinates(xMax, yMax):
    for x in range(1, xMax+1):
        for y in range(1, yMax+1):
            print(f"( {x} , {y} )  ", end="")
        print()
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 ) 

//

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

//

# be careful! 这些代码与之前的有什么不同?
def printMysteryStarShape(n):
    for row in range(n):
        print(row, end=" ")
        for col in range(row):
            print("*", end=" ")
        print()
printMysteryStarShape(5)
0 
1 * 
2 * * 
3 * * * 
4 * * * * 

row是行号,从零开始

while循环
# 我不知道它什么时候停下来
def leftmostDigit(n):
    n = abs(n)
    while n >= 10:
        n = n//10
    return n 
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
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 
break and continue

与c语言一样,continue是跳过本次循环,break是终止这一层循环

死循环

while True:

//

for循环耗时很多,

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

第一个找质数函数与第二个找指数函数结果相同,而第一个是遍历到n-1

第二个遍历到n0.5**,时间就会快很多

//

找出第n位质数

ef nthPrime(n):
    found = 0
    guess = 0
    while found <= n:
        guess += 1
        if fasterIsPrime(guess):
            found += 1
    return guess
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!

字符串string

四种引号

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

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

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

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

跟文学上的用法差不多

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

换行符号

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

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

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

下面这个例子可以秒杀马里奥,想要换行输出就需要用这种三个引号

排除换行

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

转义字符

print("双引号:\"")
双引号:"
print("反斜线:\\")
反斜线:\
print("换\n行")
换
行
print("这个是\t制\t表\t符\n也叫\t跳\t格\t键")
这个是	制	表	符
也叫	跳	格	键

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

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

s 的长度为: 7

repr() vs. print()

s1 = "Data\tWhale"
s2 = "Data        Whale"
print("s1:", s1)
print("s2:", s2)
s1: Data	Whale
s2: Data    Whale

输出虽然是一样的,但是他们不是相等的

s1 == s2

False

repr可以识别整个字符串的内容

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

一些字符串常量

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








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

字符串的加减

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

最后一行会报错因为3不是字符串

in运算

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

“A" in "B"

B中有字串和A相同就返回True,大小写敏感

字符串索引和切片

单个字符索引

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

s = "Datawhale"
print(s)
print(s[0])
print(s[1])
print(s[2])
print(s[3])
Datawhale
D
a
t
a
len(s)
9
print(s[len(s)-1])
e
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

负数索引

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

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

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

切片的默认参数

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

切片的第三个参数 step

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

翻转字符串

# 可以,但是不优雅
print(s[::-1])
elahwataD:
# 也可以,但是还是不够优雅
print("".join(reversed(s)))
elahwataD
# 实在是太优雅辣
def reverseString(s):
    return s[::-1]

print(reverseString(s))
elahwataD

字符串的循环

用索引的 for 循环

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

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

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

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 里同时取出一个元素

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() 来循环

# 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() 来循环

# 跟上面一样,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, 我们希望同学们学习这个教程后能学习到聪明的办法,从容的迈入人工智能的后续学习。

chr()and ord()

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

一些字符串方法

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     
print("YYDS YYSY XSWL DDDD".lower())
print("fbi! open the door!!!".upper())
yyds yysy xswl dddd
FBI! OPEN THE DOOR!!!
print("   strip() 可以将字符串首尾的空格删除    ".strip())
strip() 可以将字符串首尾的空格删除
print("聪明办法学 Python".replace("Python", "C"))
print("Hugging LLM, Hugging Future".replace("LLM", "SD", 1)) # count = 1
聪明办法学 C
Hugging SD, Hugging Future
s = "聪明办法学Python, 就找 Datawhale"
t = s.replace("聪明办法", "")
print(t)
学Python, 就找 Datawhale
print("This is a history test".count("is"))
print("This IS a history test".count("is"))
3
2

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

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

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

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

字符串和别名

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

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

基础文件操作

Open() 函数

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

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

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

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

file = open("chap6_demo.txt", "w")
dw_text = "Datawhale"
file.write(dw_text)
file.close()
file = open('chap6_demo.txt', 'r')
print(type(file))
<class '_io.TextIOWrapper'>

文件对象

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

  • close( ): 关闭文件
  • 在r与rb模式下:
    • read(): 读取整个文件
    • readline(): 读取文件的一行
    • readlines(): 读取文件的所有行
  • 在w与a模式下:
    • write():
    • writelines():

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

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

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

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

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

## 以 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 模式操作。

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

文件操作推荐使用 with open("xxx") as yyy,这样就不用写 f.close()

标签:文件,False,用法,print,循环,file,字符串,True
From: https://www.cnblogs.com/Shun-shun/p/17872015.html

相关文章

  • 循环与字符串
    for循环和循环范围特点:基于特定的范围,重复执行特定次数的操作for循环中循环次数range的表示其中range(x,y)表示包含x,但不包含y,即左闭右开defsumFrom(m,n):returnsum(range(m,n+1))m=5n=10sumFrom(m,n)此时输出就为45,即5+6+7+8+9+10=45range默认起始为0,即range(5)表示0-......
  • 聪明办法学python(字符串)
    字符串编写方式单引号,双引号(如果已存在一种,可用另一种引号包裹字符串,或用转义字符),三引号均可原始字符串在字符串前加"r",使字符串内的转义字符不再有效跨行字符串在每一行的末尾加上一个"\"用’‘’‘’‘或”“”“”“包裹字符串字符串字符串的运算1.字符串的......
  • Python:循环,字符串
    Python:循环,字符串循环For循环range()左闭右开区间:省略第一个参数:默认起始范围是零添加第三个参数:步长defsumfroom(m,n):total=0foriinrange(m,n+1):total+=xreturntotal#等价于下面的defsumfroom(m,n):returnsum(range(m,n+1))for循环嵌套#矩阵(补......
  • java练习:json字符串转map、arrayList
    使用依赖包:<dependency><groupId>com.alibaba.fastjson2</groupId><artifactId>fastjson2</artifactId><version>2.0.0</version></dependency>获取数据:packagecom.example......
  • Java使用三种方式循环输出Map集合
    先新建一个Map集合 1、通过entrySet获取到键值实现对象 2、通过keySet()获取键值的集合获取值3、迭代器 ......
  • java集合框架(一)之Map的常见使用及循环输出的五中方式
    Map的常见使用创建一个Mpa对象及新增键值对 获取到一个键值对get(k) containsKey(objectkey)判断集合中是否包含指定的键包含返回true,不包合返回false  remove(Objectkey,Objectvalue);把指定的键和元素在Map集合中删除 Map的五种循环输出方式 1.通过......
  • 集合框架(一)Map的常见使用及循环 的五种方式
    第一步新建Map集合 1.循环输出所有键值对 2.通过entrySet获取到键值实现对象 3.通过values直接获取值的集合(缺点:没有key(键)) 4.通过keySet()获取键值的集合获取值5.迭代器 ......
  • 【Java入门】集合框架介绍与集合框架(一)Map的常见使用及循环的五种方式
     1.集合框架-数组的长度是固定的,集合的长度是可变的。-使用Java类封装出一个个容器类,开发者只需要直接调用即可,不用再手动创建容器类。-集合是Java中提供的一种容器,可以用来存储多个数据,根据不同存储方式形成的体系结构,就叫做集合框架体系(掌握)。集合也时常被称为容器。 ......
  • 笔记06:循环和字符串
    笔记06:循环while循环whileconditionisTrue: statement(s) ifcondition: break else:continueelse:break语句跳出循环体continue语句跳出循环体并回到循环体的判断位置else语句当循环正常结束时,进行else语句for循环forvariablein可迭代对象: statement(s......
  • 循环和字符串·
    循环FOR循环和循环范围sites=["Baidu","Google","Runoob","Taobao"]forsiteinsites:print(site)以上代码执行输出结果为:BaiduGoogleRunoobTaobaoFOR循环的特点基于提供的范围,重复执行特定次数的操作range是什么东西range(x,y)是左闭右开区间,包含x,不包含ysum(ran......