Python Day-String 使用循环函数逻辑
1)replace(): 返回指定值替换为指定值的字符串。
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
输出:
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))
输出:
137348796892288 137348796892288 137348796892288 137348796892288 137348795520944
因此对于最后一个打印语句,已经创建了新的内存,并且字符串无法更改。
2)rfind() 和 rindex() 之间的区别:
在字符串中搜索指定值并返回找到该值的最后位置。
示例:1
txt = "Mi casa, su casa." x = txt.rfind("basa") print(x) x = txt.rindex("basa") print(x)
输出:
-1 ValueError: substring not found
-->在 rfind() 中,如果未找到字符串,则返回 -1。
-->在 rindex() 中,如果未找到字符串,则返回 valueError。
示例:2(逻辑)
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')
输出:
10
3) split(): 在指定分隔符处分割字符串,并返回一个列表。
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
输出:
Today is Wednesday
以上是Python Day-String 使用循环函数逻辑的详细内容。更多信息请关注PHP中文网其他相关文章!

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

使用FiddlerEverywhere进行中间人读取时如何避免被检测到当你使用FiddlerEverywhere...

如何在10小时内教计算机小白编程基础?如果你只有10个小时来教计算机小白一些编程知识,你会选择教些什么�...

攻克Investing.com的反爬虫策略许多人尝试爬取Investing.com(https://cn.investing.com/news/latest-news)的新闻数据时,常常�...

Python3.6环境下加载pickle文件报错:ModuleNotFoundError:Nomodulenamed...

使用Scapy爬虫时管道文件无法写入的原因探讨在学习和使用Scapy爬虫进行数据持久化存储时,可能会遇到管道文�...
