Python Day06

字符串文字

四种引号

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

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

print('单引号')
print("双引号")
print('''三个单引号''')
print("""三个双引号""")
​
"""
结果为:
单引号
双引号
三个单引号
三个双引号
"""

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

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

# 为了写出这样的句子
print("聪明办法学 Python 第二版的课程简称是 'P2S'")
如果我们只用一种引号呢?

# 这会导致语法错误,Python 无法正确判断一个字符串的终止位置
print("聪明办法学 Python 第二版的课程简称是 "P2S"")
​
# 这会导致语法错误,Python 无法正确判断一个字符串的终止位置
print("聪明办法学 Python 第二版的课程简称是 "P2S"")
  Cell In [4], line 2
    print("聪明办法学 Python 第二版的课程简称是 "P2S"")
                                   ^
SyntaxError: invalid syntax

字符串中的换行符号

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

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

# 这两个 print() 在做同样的事情 
print("Data\nwhale")  # \n 是一个单独的换行符号
​
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
"""
print(s1 == s2)
#结果为:False
​
print(repr(s1))
print(repr(s2))
#打印结果:
"""
'Data\tWhale'
'Data        Whale'
"""

一些字符串常量

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

一些字符串的运算

字符串的加减

print("abc" + "def")
print("abc" * 3)
​
"""
打印结果:
abcdef
abcabcabc
"""

in 运算

print("ring" in "strings") 
print("wow" in "amazing!") 
print("Yes" in "yes!") 
print("" in "No way!") 
print("聪明" in "聪明办法学 Python") 
​
"""
打印结果:
True
False
False
True
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) # Datawhale
print(s[-5]) # w
print(s[-4]) # h
print(s[-3]) # a 
print(s[-2]) # l
print(s[-1]) # e
用切片来获取字符串的一部分
print(s[0:4]) # Date
print(s[4:9]) # whale
切片的默认参数
print(s[:4]) # Date
print(s[4:]) # whale
print(s[:]) # Datewhale
切片的第三个参数 step
print(s[:9:3]) # Daa
print(s[1:4:2]) # aa
翻转字符串
# 可以,但是不优雅
print(s[::-1])
# 也可以,但是还是不够优雅
print("".join(reversed(s)))
# 实在是太优雅辣
def reverseString(s):
    return s[::-1]
​
print(reverseString(s))
​
# 结果均为:elahwataD

字符串的循环

用索引的 for 循环

for i in range(len(s)):
    print(i, s[i])

不用索引(in

for c in s:
    print(c)

split() 来循环

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

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

例子:回文判断

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

def isPalindrome1(s):
    return (s == reverseString(s))
    
def isPalindrome2(s):
    for i in range(len(s)):
        if (s[i] != s[len(s)-1-i]):
            return False
    return True
​
def isPalindrome3(s):
    for i in range(len(s)):
        if (s[i] != s[-1-i]):
            return False
    return True
    
def isPalindrome4(s):
    while (len(s) > 1):
        if (s[0] != s[-1]):
            return False
        s = s[1:-1]
    return True
​
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()
name = input("输入你的名字: ")
print("Hi, " + name + ", 你的名字有 " + str(len(name)) + " 个字!")
​
# 输入你的名字: Datawhale
# Hi, Datawhale, 你的名字有 9 个字!
char() 和 ord()
print(ord("A"))
print(chr(65))
print(
    chr(
        ord("A") + 1
    )
)
print(chr(ord("A") + ord(" ")))
​
# 65 
# A
# B
# a

一些字符串方法

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
print("This is a history test".count("is")) # 3
print("This IS a history test".count("is")) # 2
print("Dogs and cats!".startswith("Do")) # True
print("Dogs and cats!".startswith("Don't")) # False
print("Dogs and cats!".startswith("Do")) # True
print("Dogs and cats!".startswith("Don't")) # False
print("Dogs and cats!".find("and")) # 5
print("Dogs and cats!".find("or")) # -1
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
      <a href='vscode-notebook-cell:/c%3A/Coding/Datawhale/Python_Tutorial/learn-python-the-smart-way-v2/slides/chapter_6-Strings.ipynb#Y221sZmlsZQ%3D%3D?line=0'>1</a> print("Dogs and cats!".index("and"))
----> <a href='vscode-notebook-cell:/c%3A/Coding/Datawhale/Python_Tutorial/learn-python-the-smart-way-v2/slides/chapter_6-Strings.ipynb#Y221sZmlsZQ%3D%3D?line=1'>2</a> print("Dogs and cats!".index("or"))
​
ValueError: substring not found
"""

f-string 格式化字符串

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

其他格式化字符串的方法

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

  • % 操作

  • format() 方法

字符串是不可变的

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
      <a href='vscode-notebook-cell:/c%3A/Coding/Datawhale/Python_Tutorial/learn-python-the-smart-way-v2/slides/chapter_6-Strings.ipynb#Y230sZmlsZQ%3D%3D?line=0'>1</a> s = "Datawhale"
----> <a href='vscode-notebook-cell:/c%3A/Coding/Datawhale/Python_Tutorial/learn-python-the-smart-way-v2/slides/chapter_6-Strings.ipynb#Y230sZmlsZQ%3D%3D?line=1'>2</a> s[3] = "e"
​
TypeError: 'str' object does not support item assignment
"""

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

字符串和别名

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

s = 'Data'  # s 引用了字符串 “Data”
t = s      # t 只是 “Data” 的一个只读别名
s += 'whale'
print(s) # Datawhale
print(t) # Data
​
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
----> <a href='vscode-notebook-cell:/c%3A/Coding/Datawhale/Python_Tutorial/learn-python-the-smart-way-v2/slides/chapter_6-Strings.ipynb#Y236sZmlsZQ%3D%3D?line=0'>1</a> t[3] = "e"
​
TypeError: 'str' object does not support item assignment
"""

基础文件操作

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( ): 关闭文件

  • rrb模式下:

    • read(): 读取整个文件

    • readline(): 读取文件的一行

    • readlines(): 读取文件的所有行

  • wa模式下:

    • 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 语句

我不想写 close() 啦!

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.
"""
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]))
"""
with open("ZenOfPy.py", "w", encoding="utf-8") as file:
    file.write(Caesar_cipher)
    print(len(Caesar_cipher))
# 1003


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() 啦。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值