加入收藏 | 设为首页 | 会员中心 | 我要投稿 源码网 (https://www.900php.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

python字符串之函数篇

发布时间:2022-10-24 14:32:20 所属栏目:MsSql教程 来源:网络
导读: 查找相关,替换
find(字符) 返回位置,若有,返回字母第一次出现的位置若不在则返回-1
s1 = "I am a good student"
position=s1.find('R')
print(position) # -1
position=s1.fi

查找相关,替换

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(字符Mssq字符串函数,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)

(编辑:源码网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!