
1)replace(): 返回指定值替换为指定值的字符串。
txt = "i like bananas"already = "bananas"new = "apples"l = len(already) # l = 7start = 0 end = l while end<=len(txt): if txt[start:end] == 'bananas': print(txt[:start],new) start+=1 end+=1
输出:
i like apples
–> 在python中,一切都是对象。
–> 每个不同的对象有不同的内存空间。
–> 字符串是不可变的:
–> 不可变:不可更改 – மாறாது。
–> 如果我们尝试编辑现有字符串,它不会改变。相反,将创建一个新的内存来存储新值。
–>相同的字符串可以引用相同的内存。
示例:
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))
输出:
137348796892288137348796892288137348796892288137348796892288137348795520944
因此对于最后一个打印语句,已经创建了新的内存,并且字符串无法更改。
2)rfind() 和 rindex() 之间的区别:
在字符串中搜索指定值并返回找到该值的最后位置。
示例:1
txt = "mi casa, su casa."x = txt.rfind("basa")print(x) x = txt.rindex("basa")print(x)
输出:
-1valueerror: substring not found
–>在 rfind() 中如果未找到字符串则返回 -1。
–>in rindex() 如果找不到字符串则返回 valueerror。
示例:2(逻辑)
txt = "python is my favourite language"key = 'my'l = len(key)start = len(txt) - lend = len(txt)while start >= 0: if txt[start:end] == key: print(start) break start -= 1 end -= 1else: print('-1 or valueerror')
输出:
10
3) split(): 在指定分隔符处分割字符串,并返回一个列表。
txt = "today is wednesday"word = ''start = 0i = 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
输出:
TodayisWednesday
以上就是Python Day-String 使用循环函数逻辑的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1354804.html
微信扫一扫
支付宝扫一扫