第六章 字符串操作
1.字符串处理
(1) 双引号:字符串用双引号开始和结束,这样在该语句中的单引号是字符串的一部分。
(2) 转义字符:直接在字符串中输入一些一般不能放在字符串的字符(单引号、倒斜杠等)
符号 | 作用 |
---|---|
\ ’ 、 \ " | 单引号、双引号 |
\ \ | 倒斜杠 |
\t | 制表符 |
\n | 换行符 |
ps:制表符作用:对齐表格各列
print('name\tage\tgrade')
print('Bob\t12\t81')
print('Eve\t11\t66')
(3)原始字符串:在字符串开始的引号之前加上r,其作用是忽略该字符串中的所有转义字符,打印出字符串中所有倒斜杠。
(4) 三重引号:字符串的起止是3个单引号或者3个双引号,其作用是三重引号之间的所有引号、制表符、换行符等都被认为是字符串的一部分(其中的任何输入格式都被保留);此外,三重引号也常常用于多行注释。(#字符表示这一行是注释)
2.字符串的下标和切片
其基本内容和week_3中的2.列表下标 基本一致,特别的在字符串中的空格字符也要占一个下标,且字符串切片没有修改原来的字符串(字符串是不可变数据类型。
3.相关语句或函数
(1)in 和 not in 语句
和列表操作一致,是检查一个字符串是否在另一个字符串中存在。
(2)upper()、lower()函数
spam=‘Hello’
函数 | 作用 | 示例 |
---|---|---|
upper() | 返回一个将原字符串大写的字符串 | spam.upper()=‘HELLO’ |
lower() | 返回一个将原字符串大写的字符串 | spam.lower()=‘hello’ |
(3) isX()系列函数
调用格式为:spam.isupper()=False
函数语句 | 作用 |
---|---|
isupper()、islower() | 检验字符串中所有字母是否为大写(或小写) |
isalpha() | 检验字符串是否只包含字母,且非空 |
isalnum() | 检验字符串是否只包含字母和数字,且非空 |
isdecimal() | 检验字符串是否只包含数字 ,且非空 |
isspace() | 检验字符串是否只包含空格、制表符和换行符,且非空 |
istitle() | 检验字符串是否都是以大写字符开头、后面都是小写字母的单词 |
ps.可以用于密码设置
(4) startswith()、endswith()函数
作用:检验所调用的字符串是否以设定的参数开始或结束。
例:spam.startswith(‘He’)=True,spam.endswith(‘llo’)=False.
(5) join()、split()函数
join()函数作用:在列表(参数)个元素之间插入一个字符串。
例:
split()函数作用:将字符串按某个参数分割成列表
例:
(6)对齐函数
函数 | 作用 |
---|---|
rjust() | 右对齐 |
ljust() | 左对齐 |
center() | 居中 |
ps.以上三个函数括号内的的参数有两个,第一个是该行字符总个数;第二个是其他位置的填充物,为字符格式(‘x’、’-'等)
(7) 删除字符函数
函数 | 作用 |
---|---|
strip() | 删除两侧的指定字符(参数) |
rstrip() | 删除右侧的指定字符(参数) |
lstrip() | 删除两侧的指定字符(参数) |
ps.strip()函数参数的字符串中的字符顺序不重要,因为函数的目的是删除括号中包含的(在两侧)所有字符。
(8)pyperclip模块的拷贝粘贴函数
语句 | 作用 |
---|---|
pyperclip.copy() | 拷贝括号内的字符串 |
pyperclip.paste() | 粘贴剪切板的字符串 |
ps.pyperclip模块是第三方模块,需要下载并调用时才能使用这两个函数。
4.项目实践
(1)口令保管箱
失败了,不知道怎么运行不了,明明代码都一样,可能时附录B的神秘操作没弄好
#! python38
# pw.py -An insecure password locker program
PASSWORDS= {'email':'qwer1234',
'QQ':'japdjan445',
'blog':'1234'}
import sys,pyperclip
if len(sys.argv) < 2:
print('Usage:py pw.py [account] -copy account password') #感觉是这里的问题
sys.exit ()
account=sys.argv[1] #frist command line arg is the account name #这里也没看懂
if account in PASSWARDS:
pyperclip.copy(PASSWORDS[account])
print('Password for '+account + ' copied to clipboaed')
else:
print('there is no account named '+ account)
(2)批量在多行文字前添加无序标记(*)
测试文本:
lists of animals
lists of aquarium life
lists of cultivars
#! python38
# PointAdder.py
import pyperclip
text=pyperclip.paste() #粘贴原文本到text
lines = text.split('\n') #以分隔符区分每一行
for i in range(len(lines)):
lines[i] = '*'+lines[i] #每一行前添加*号
text = '\n'.join(lines) #还原为字符串格式
pyperclip.copy(text) #新的文本复制到剪切板
效果:
*lists of animals
*lists of aquarium life
*lists of cultivars
前半部分复习作业实践(1-6章)
- 第一章(无)
- 第二章(无)
- 第三章——collatz序列(已完成)
- 第四章——逗号代码、字符图网格
**逗号代码:**编写一个函数,它以一个列表值作为参数,返回一个字符串。该字符串包含所有表项,表项之间以逗号和空格分隔,并在最后一个表项之前插入 and 。
例如,将前面的spam列表传递给函数,将返回’apples,bananas,tofu,and cats’。但是你的函数应该能够传递给它的任何列表。
spam=['apples','bananas','tofu','cats']
def func(x):
a=x[0]
if len(x)>1:
for i in range(1,len(x)-1):
a=a+', '+x[i]
a=a+',and '+ x[len(x)-1]
print(a)
func(spam[:3])
结果:‘apples, bananas,and tofu’
字符图网络:(主要是将其转置)利用grid列表打印如结果所示的图像
grid=[['.','.','.','.','.','.'],
['.','0','0','.','.','.'],
['0','0','0','0','.','.'],
['0','0','0','0','0','.'],
['.','0','0','0','0','0'],
['0','0','0','0','0','.'],
['0','0','0','0','.','.'],
['.','0','0','.','.','.'],
['.','.','.','.','.','.']]
for j in range(6):
for i in range(9):
print(grid[i][j],end=' ') #每一个符号之间添加一个空格,且不换行
print() # 每行结尾默认换行符
结果:
. . 0 0 . 0 0 . .
. 0 0 0 0 0 0 0 .
. 0 0 0 0 0 0 0 .
. . 0 0 0 0 0 . .
. . . 0 0 0 . . .
. . . . 0 . . . .
- 第五章——好玩游戏的物品清单:写一个名为 displayInventory()的函数,它接受任何可能的物品清单, 并显示对应结构;addToInventory()函数应该返回一个字典, 表示更新过的物品清单。
#原有物品展示
stuff={'rope':1,'toech':6,'gold coin':42,'dogger':1,'arrow':12} #原始清单
def dispalyinv(inventory):
print('Inventory:')
item_total=0
for k,v in inventory.items():
print(str(v)+' '+ k )
item_total+=v
print('Total munber of items:'+ str(item_total))
#dispalyinv(stuff) (调用时去掉#号)
#添加新的物品
def addtoinv(inventory,additems):
for i in additems:
if i in stuff.keys():
stuff[i]+=1 #原来存在就只增加该键对应的值
else:
stuff.setdefault(i,1) #原来不存在添加新的 键-值对
return inventory
dragonLoot=['gold coin','dagger','gold coin','gold coin','ruby'] #龙的战利品
stuff=addtoinv(stuff,dragonLoot)
dispalyinv(stuff) #展示新的物品清单
结果:
6. 第六章——表格打印:编写一个名为 printTable()的函数, 它接受字符串的列表的列表,将它显示在组织良好的表格中,每列右对齐。假定所有内层列表都包含同样数目的字符串。
#题目数据
tabledata=[['apples','oranges','cherries','banana'],
['Alice','Bob','Carol','David'],
['dogs','cats','moose','goose']]
def printTable(x):
colWidths=[0]*len(x)
for i in range(len(x)):
for j in range(len(x[0])):
if len(x[i][j])>int(colWidths[i]):
colWidths[i]=len(x[i][j]) #计算每一列的最长字符串
for j in range(len(x[0])):
for i in range(len(x)):
print(x[i][j].rjust(colWidths[i]),end=' ')
print() #每列右对齐打印
printTable(tabledata)
结果: