Python(字符串常见函数)

字符串常见函数
find
find() 从左侧查找第一次出现"!"的位置  --->下标位置
# index=s.find("!")
# print(index)  # 5


# index=s.find("#")  # 如果要查找的字符没有出现在字符串中则返回-1
# print(index)


# # rfind()  right find()


# index=s.rfind("g")  # 返回的是从右侧开始找第一次出现的字母的位置,如果要查找的字符没有出现在字符串中则返回-1
# print(index)  # 12


# print(s[:s.find("!")],s[s.find("!")+1:])
find():根据字符找位置  没有找到则返回-1
rfind
类似于 find()函数,不过是从右边开始查找.
返回的是从右侧开始找第一次出现的字母的位置,如果要查找的字符没有出现在字符串中则返回-1
index
index()跟find()方法一样,只不过如果str不在 mystr中会报一个异常.
index(): 根据字符找位置  没有找到则报错
rindex
类似于 index(),不过是从右边开始.
replace
把 mystr 中的 str1 替换成 str2,如果 count 指定,则替换不超过 count 次,最多等于count 
replace(old,new)  --->返回的是替换后的结果
s=s.replace("hello","hi")


print(s.replace("hello","hi"))


print(s.replace("atguigu","尚硅谷"))  # hi!
split
以 str 为分隔符切片 mystr,如果 maxsplit有指定值,则仅分隔 maxsplit 个子字符串
split("")  --->返回值是一个列表  ["hello","atguigu","haha"],如果参数字符没有找到,则列表中内容就是当前的字符串s
['hello atguigu haha']
s="hello#atguigu#haha"
print(s.split("#"))
partition
把mystr以str分割成三部分,str前,str自身和str后
特点: 遇到要搜索的字符则切割,就将切割的内容包含切割的字符都放到一个元组中
print(s.partition("#"))  
# 结果: ("hello","#","atguigu#haha")
rpartition
分割
类似于 partition()函数,不过是从右边开始.
splitlines
按照行分隔,返回一个包含各行作为元素的列表,按照换行符分割
# splitlines()


# s='''<!DOCTYPE html>
# <html lang="en">
# <head> 
# <title>尚硅谷办公管理系统</title> 
# </head>
# <body class="login-body">
#     欢迎登录办公管理系统!
# </body>
# </html>
#'''
startswith
检查字符串是否是以 obj 开头, 是则返回 True,否则返回 False
endswith
检查字符串是否以obj结束,如果是返回True,否则返回 False.
lower
转换 mystr 中所有大写字符为小写
upper
转换 mystr 中的小写字母为大写
lstrip
删除 mystr 左边的空白字符
rstrip
删除 mystr 字符串末尾的空白字符
strip
删除mystr字符串两端的空白字符
isspace
如果 mystr 中只包含空格,则返回 True,否则返回 False.
如果有多个空格同样返回True
count
返回 str在start和end之间 在 mystr里面出现的次数
join
mystr 中每个字符后面插入str,构造出一个新的字符串
capitalize
把字符串的第一个字符大写
title
把字符串的每个单词首字母大写
ljust
返回一个原字符串左对齐,并使用空格填充至长度 width 的新字符串
rjust
返回一个原字符串右对齐,并使用空格填充至长度 width 的新字符串
center
返回一个原字符串居中,并使用空格填充至长度 width 的新字符串
isalpha
如果 mystr 所有字符都连续的是字母 则返回 True,否则返回 False
isdigit
如果 mystr 只包含数字则返回 True 否则返回 False.
应用场景:输入数字的时候,判断是纯数字的时候,就可以转成int
isalnum
如果 mystr 所有字符都是字母或数字则返回 True,否则返回 False
案例
s='''曹操 20 男
貂蝉 18 女
吕布 20 男
小乔 18 女
周瑜 21 男
'''


print(s.splitlines())
persons=s.splitlines()  # list


for i in persons:
person=i.split(" ")
print("姓名:{0[0]},年龄:{0[1]},性别:{0[2]}".format(person))




自由主题

猜你喜欢

转载自blog.csdn.net/qq_42240071/article/details/80409810