目录
1.字符串概念和注意事项
2.字符串内置函数
3.字符串的索引、切片和遍历
4.字符串运算符
5.字符串常用方法
性质判断
开头结尾判断
是否存在某个子串
大小写等格式转化
子串替换
删除两端空白字符
格式化字符串
分割与合并
6.字符串模板
7.exec 函数
8.字符串加密和解密
1.字符串概念和注意事项
s1 = "abc"
s2 = "abc"
print(id(s1))
print(id(s1) == id(s2)) # True
s = "abc"
s[2] = 'x'
报错提示
TypeError: 'str' object does not support item assignment
解释:s = "abc"表示生成了一个s变量,s = "abc"语句后,在内存中开辟了一块地址,专门用来存放"abc"这个字符串,且s当前所代表的内存地址是"abc"的地址。字符串对象不可变指的是"abc"是不可变的,s[0]='x'操作就是试图将存放在内存中的"abc"的第一个元素改为'x',这是不允许的。
如果你想要修改字符串中的某个字符,你必须创建一个新的字符串。例如,你可以通过切片(slicing)和字符串连接(concatenation)等来实现这一点
s = "abc"
s2 = s[:2] + 'x'
print(s2) # abx
也可以对变量重新赋值,本质是对变量s更换了一个地址
s = "abc"
print(id(s))
s = "abx"
print(id(s))
2.字符串内置函数
常用的有len获取长度,max获取最大字符等
s = "ac1"
print(len(s)) # 返回字符串的长度,3
print(max(s)) # 返回字符串中“最大”的字符,c
print(min(s)) # 返回字符串中“最小”的字符,1
3.字符串的索引、切片和遍历
s[0: len(s)] = ss[: 4] = s[0: 4]
s[2: ] = s[2: len(s)]
s[ : ] = ss[ : -1] = s[0: -1] = s[0 : -1 + len(s)]
s[-2 : ] = s[-2 : len(s)] = s[-2 + len(s) : len(s)]
s[-5 : -2] = s[-5 + len(s) : -2 + len(s)]s[1 : y] = s[1 : len(s)] # 如果 y >= len(s)的话
s[2 : 1] = '' # 空串
s[2 : 2] = '' # 空串
for ch in "abcd":print(ch, end=" ")
# a b c d
4.字符串运算符
print('ab' + 'cd') # abcd
print('ab' * 2) # abab
print(2 * 'ab') # abab
print('He' in "He and I") # True
print('he' in "He and I") # False
print('he' not in "he ta") # False
print("abc" < "abcd") # True
print("abd" < "a1c") # False
print("Jane" < "Jacksandffs") # False
5.字符串常用方法
性质判断
返回值为布尔变量 bool
s.isalnum(),如果字符串中的字符只有数字或者字母,则返回 True
s.isalpha(),如果字符串中的字符只有字母,则返回 True
s.isdigit(),如果字符串中的字符只有数字,则返回 True
s.isdecimal(),如果字符是十进制数字,则返回 True
print('234 '.isdigit()) # False
print('234'.isdigit()) # True
s.isidentifier(),如果这个字符串满足 python 标识符的要求,则返回 True
print('_radius'.isidentifier()) # True
print('2radius'.isidentifier()) # False
print('2ad '.islower()) # True
print('2Ad '.islower()) # False
print('2AD '.isupper()) # True
print('2 '.isspace()) # False
print(' '.isspace()) # True
开头结尾判断
print('radius'.endswith("usa")) # False
print('radius'.startswith("ra")) # True
是否存在某个子串
s.find(s1, starti, endi),返回字符串 s 中第一次出现子串 s1 时,此时 s1 第一个字符的下标;找不到返回-1
s.rfind(s1, starti, endi),返回字符串 s 中最后一次出现子串 s1 时,此时 s1 第一个字符的下标;找不到返回-1
print("mynameisname".find('name')) # 2
print("mynameisname".rfind('name')) # 8
print("xxxxabc".count('xx')) # 2
print("xxxxabcxxx".count('xx')) # 3data = "hello world"
if data.find("age") == -1:print("not find")
else:print("exist")
大小写等格式转化
s.capitalize(),返回只大写第一个字符的字符串
s.lower(),返回全是小写的字符串
s.upper(),返回全是大写的字符串
s.title(),返回只将每个单词首字母大写的字符串
s.swapcase(),返回大小写互换的字符串,就是大写字母变成小写,小写字母变大写
print("the happy of python".title()) # The Happy Of Python
子串替换
s = "abcd"
s1 = s.replace("ab", "xyz")
print(s) # abcd
print(s1) # xyzcd
技巧:替换为空字符串表示删除
s = "abcdab"
s1 = s.replace("ab", "")
print(s) # abcd
print(s1) # cd
删除两端空白字符
s = " x y z "
s1 = s.strip()
print(f"({s1})") # (x y z)
格式化字符串
s = "abcd"
s1 = s.center(10)
print(f"({s1})") # ( abcd )
分割与合并
mystr = "A1021879743 # 1021879743 # www.1021879743@qq.com"
mylist = mystr.split(" # ") # 按照 # 切割,返回列表
print(mylist) # ['A1021879743', '1021879743', 'www.1021879743@qq.com']
mystr = "88548 n 小姐 女 22 162"
mylist = mystr.split(" ", 2) # 按空格切割,切割 2 次就停止
print(mylist) # ['88548', 'n', '小姐 女 22 162']
mystr = """88548
n 小姐 女
22 162"""
mylist = mystr.splitlines() # 根据换行符切割
print(mylist) # ['88548 ', 'n 小姐 女', '22 162']
字符串partition()函数
partition()方法用来根据指定的分隔符将字符串进行分割。
如果字符串包含指定的分隔符,则返回一个3元的元组,第一个为分隔符左边的子串,第二个为分隔符本身,第三个为分隔符右边的子串。
如果未找到separator参数,字符串本身和两个空字符串
data = "name=bob;age=10"
ret = data.partition(";")
print(ret) # ('name=bob', ';', 'age=10')data = "name=bob"
ret = data.partition(";")
print(ret) # ('name=bob', '', '')
字符串合并:join 函数
将列表等可迭代对象按特定符号拼接成字符串
mystr = "这是一个国家级机密"
lst = list(mystr)
print(lst) # ['这', '是', '一', '个', '国', '家', '级', '机', '密']newstr = "#".join(mystr)
print(newstr) # 这#是#一#个#国#家#级#机#密
6.字符串模板
from string import Template # string 模块导入 Template# print(type(Template)) # <class 'string._TemplateMetaclass'># 搭建模板
mystr = Template("hi, $name 你是 $baby")# 模板使用
print(mystr.substitute(name="罗翔", baby="老师"))
print(mystr.substitute(name="张三", baby="学生"))'''
hi, 罗翔 你是 老师
hi, 张三 你是 学生
'''
7.exec 函数
作用:将字符串当做命令行语句来执行
import os
mystr = 'os.system("notepad")'
exec(mystr)
8.字符串加密和解密
加密:按指定规律将字符串的每一个字符变为另一个字符。
解密:将加密后的内容指定规律还原原内容。
第一种:自定义加码:str.maketrans(old, new)
mystr = "hello python 我,我,你"
table = str.maketrans("我你 x", "他它 y") # 我替换成他,你替换成它,x 替换成 y
print(mystr) # hello python 我,我,你
print(mystr.translate(table)) # hello python 他,他,它
realStr = "这是一个国家级机密"
key = 5faceStr = [chr(ord(x) + key) for x in list(realStr)]
print(faceStr) # ['连', '昴', '丅', '丯', '圂', '宻', '纬', '朿', '寋']correctStrList = [chr(ord(x) - key) for x in list(faceStr)]
correctStr = "".join(correctStrList)
print(correctStr)
这些是最基础最简单的加密解密,日常使用足够。
end