文章目录
前言
提示:本节主要介绍python序列结构,包括字符串、列表、元组、字典、集合
一、字符串
(一)基础知识
1. 字符串定义
str1 = "What's your name" # 字符串中出现单引号,可以用双引号
str2 = 'What\'s your name'
str3 = "\"Yes\",he says." # 当单引号中出现单引号,或者双引号中出现双引号,可以使用反斜杠\对字符原样输出。
str4 = """how
are
you
""" # 使用三引号可以换行输出
2.字符串大小写转换
s.capitalize() # 首字母大写
s.upper() # 全部大写
s.lower() # 全部小写
s.swapcase() # 大小写互换
s.title() # 每个用特殊字符或数字隔开的单词首字母大写
3.居中(用空白/其他字符填充)
# 语法:str.center(width, fillchar = None)
s1 = s.center(20,'%') # 用%填充
s2 = s.center(20) # 用空白填充
4.查找
# str.find()通过元素找索引,找到返回索引,找不到返回-1
# str.index()通过元素找索引,找到返回索引,找不到返回error
s = 'Andrew'
s_1 = s.find('w')
s_1 = s.index('e')
5. 删除字符串前后的空格
s = " alexW # % 123 "
s_1 = s.strip()
s_2 = s.strip(%)
# 注意:str.strip()的方式只能暂时删除,要想永久删除字符串的空白,需将删除的操作关联到变量。
6. 计算字符串中某字符/某字符串的个数
str.count(s)
7. 分割(相当于str→list)
str.split()
str.split(':')
8.字符串替换 replace函数
s = '小小小'
s1 = s.replace('小','大',1) # 只替换第一个出现的,默认替换所有
9.is系列
str.isdigit() # 是否由数字组成
str.isalpha() # 是否由字母组成
str.isalnum() # 是否由字母或数字组成
(二)例题
1. 替换
Write a Python function that takes in a string and returns a modified string replacing each letter ‘T’ and ‘t’ with a ‘*’.
def allBut(s):
print(s.replace('T','*').replace('t','*'))
2. Caesar encryption
Write a Python function caesarEncryption(s, n)
to convert all characters in string s into lowercase and create a Caesar encryption with shift n, leaving the non-letter characters unchanged, then return the result.
def caesarEncyption(s,n):
t = s.lower()
s1 = ""
for i