您的位置:首页 > 其它

jeapedu 31 字符串切片删除子串

2018-02-28 23:18 204 查看
链接: https://pan.baidu.com/s/1o9Vr5SQ 密码: xf3r

# 1 use slice to find substring pos
# 2 separate string with blank space
# 3 delete certain substring
# 4 delete extra the, keep first on
#   s = "hello the world these wether neither"
# 5 replace certain substring

# 3 delete certain substring
print("-----")
s = "helxixxixlxxo jeapxixedu.com"
sub = "xix"
i = 0
while i < len(s): # 遍历i
print(i, s[i])
if s[i:i + len(sub)] == sub: #如果从i开始的s有=sub的,
s = s[:i] + s[i + len(sub):] #让 s[:i] 和 后面的合并
print(s)
i -= 1
i += 1
print(s)

# 4 delete extra the, keep first on
#   s = "hello the world these wether neither"
s = "hello the world these wether neither"
sub = "the"
i = 0
keepon = 1
count = 0
while i < len(s):
if s[i:i + len(sub)] == sub:
if count < keepon:
count += 1
else:
s = s[:i] + s[i + len(sub):]
count += 1
i -= 1
i += 1
print(s)

# 5 replace certain substring
s = "helxixxixlxxo jeapxixedu.com"
sub = "xix"
rep = "thee"
i = 0
while i < len(s):
print(i, s[i])
if s[i:i + len(sub)] == sub:
s = s[:i] + rep + s[i + len(sub):]
print(s)
i += len(rep)
else:
i += 1
print(s)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: