字符操作02

find 

可以用来寻找到一串字符中的某一段字符串

# 查找字符串
i = "dsashdj"
j = i.find('d')
print(j,type(j))
View Code

注意:find返回的时字符串的索引。如若未检索到则返回-1。

index

与find相同,通过元素找索引。

i = "dsashdj"
j = i.find('A')
j1 = i.index('A')
print(j,type(j))
print(j1,type(j1))
View Code

与find不同的是,index如果没有找到,会直接报错。

strip 默认去前后空格

#去左右的空格
s = '    dsjjkf  hdjas  jhdfj     '
s1 = s.strip()
print(s1)
View Code

作用:

可以解决对有些用户输入时信息时随手加空格而导致与数据库信息不匹配出错的问题。

例如:

username = input("请输入信息:").strip()
if username == '套你大象':
    print("套你大象")
View Code

当然,strip还可以填充来删除其他任意字符串。例如:

i = s.strip('$fm')

代表删除s中所有的¥,f,m。而且不限顺序。

分支 rstrip 和 lstrip

即从左开始删和从右开始删。

注意:

无论strip还其分支,都是删一次。即填充一次

count 计数

可以输出一段字符串中某一字符或字符串个数

s = '    dsjjkf  hdjas  jhdfj     '
s1 = s.count('j')
print(s1)
View Code

split

拆分

s = 'dsj jkfhdja sjhdfj'
s1 = s.split()
print(s1)
View Code
默认以空格为拆分
还可以设置以其他字符为拆分
原文地址:https://www.cnblogs.com/zly9527/p/11204122.html