Python Day-String 使用循环函数逻辑(函数.逻辑.循环.Python.Day...)
1)replace(): 返回指定值替换为指定值的字符串。
PHP
txt = "i like bananas"
already = "bananas"
new = "apples"
l = len(already) # l = 7
start = 0
end = l
while end<=len(txt):
if txt[start:end] == 'bananas':
print(txt[:start],new)
start+=1
end+=1
输出:
PHP
i like apples
--> 在python中,一切都是对象。
--> 每个不同的对象有不同的内存空间。
--> 字符串是不可变的:
--> 不可变:不可更改 - மாறாது。
--> 如果我们尝试编辑现有字符串,它不会改变。相反,将创建一个新的内存来存储新值。
-->相同的字符串可以引用相同的内存。
示例:
PHP
country1 = 'india'
country2 = 'india'
country3 = 'india'
country4 = 'india'
print(id(country1))
print(id(country2))
print(id(country3))
print(id(country4))
country1 = "singapore"
print(id(country1))
输出:
PHP
137348796892288
137348796892288
137348796892288
137348796892288
137348795520944
因此对于最后一个打印语句,已经创建了新的内存,并且字符串无法更改。
2)rfind() 和 rindex() 之间的区别:
在字符串中搜索指定值并返回找到该值的最后位置。
示例:1
PHP
txt = "mi casa, su casa."
x = txt.rfind("basa")
print(x)
x = txt.rindex("basa")
print(x)
输出:
PHP
-1
valueerror: substring not found
-->在 rfind() 中如果未找到字符串则返回 -1。
-->in rindex() 如果找不到字符串则返回 valueerror。
示例:2(逻辑)
PHP
txt = "python is my favourite language"
key = 'my'
l = len(key)
start = len(txt) - l
end = len(txt)
while start >= 0:
if txt[start:end] == key:
print(start)
break
start -= 1
end -= 1
else:
print('-1 or valueerror')
输出:
PHP
10
3) split(): 在指定分隔符处分割字符串,并返回一个列表。
PHP
txt = "today is wednesday"
word = ''
start = 0
i = 0
while i<len(txt):
if txt[i]==' ':
print(txt[start:i])
start = i+1
elif i == len(txt)-1:
print(txt[start:i+1])
i+=1
输出:
PHP
Today
is
Wednesday
以上就是Python Day-String 使用循环函数逻辑的详细内容,更多请关注知识资源分享宝库其它相关文章!