Python 参考手册www.w3school.com.cnPython 字符串方法www.w3school.com.cn
查找相关,替换
find(字符) 返回位置,若有,返回字母第一次出现的位置若不在则返回-1
s1 = "I am a good student"
position=s1.find('R')
print(position) # -1
position=s1.find('a')
print(position) # 2 ,下标从0开始,空格也算
find(字符,开始位置) 指定开始位置查找
position=s1.find('a',3)
print(position)
find(字符,star,end) 指定开始位置和结束位置查找
position=s1.find('a',3,len(s1)-1)
print(position)rfind() 从右侧开始找
从路径中找到一个文件的名字
url='https://www.baidu.com/img/bd_logo1.png'
p=url.rfind('/') #从右侧开始检索
print(p) # 25返回的地址仍然是从左边开始数
filename = url[p+1:]
print(filename) #bd_logo1.png
index()函数和find()一样,只不过index()如果找不到会报异常,find会返回-1
replace(字符,新字符) 替换
s2=s1.replace(' ','$')
print(s2) # 把空格替换为$,I$am$a$good$student
#replace(字符,新字符,替换的次数)
s2=s1.replace(' ','$',2)
print(s2) # I$am$a good student
encode(编码格式) 编码 decode(解码格式)解码
由于电脑不能识别中文,所以输入的中文必须编码另外一种语言unicode
msg='上课了,放学了!'
result=msg.encode('utf-8')
print(result)
# b'\xe4\xb8\x8a\xe8\xaf\xbe\xe4\xba\x86\xef\xbc\x8c\xe6\x94\xbe\xe5\xad\xa6\xe4\xba\x86\xef\xbc\x81'
解码
m=result.decode('utf-8')
print(m)
startswith(字符) endswith(字符) 判断是否同样的格式开头结尾,返回值是布尔类型
s='hello'
re = s.startswith('he')
print(re)
文件上传时判断是否以图片格式结尾
path = input("请输入地址:") # C:\Users\Public\Pictures\Sample Pictures\th.jpg
p = path.rfind('\\') #从右边寻找图片的名字 \需要转义
filename =path[p+1:]
if filename.endswith('jpg' or filename.endswith('png'):
print('是以图片格式上传的')
else:
print('请上传正确的图片格式')
lstrip()去掉左侧空格 rstrip()去掉右侧空格 strip()去掉左右两侧空格
s=' hello '
rs=s.lstrip()
print(rs)
rs=rs.rstrip()
print(rs)
python字符串基础zhuanlan.zhihu.com