字符串操作补充

📅 2026/8/27 13:35:12
字符串操作补充
目录1.字符串的查找a.许多时候我们想知道某个特定的单词或短语是否在一篇文章当中我们可以运用查找解决这一问题我们以字符串在单词中的查找为例b.讨论完字符串在不在单词之后我们的下一个目标是字符串的具体位置在哪c.接下来让我们尝试一下提取特定位置的字符2. 字符串的变大与变小3.字符的替换4.清理空格1.字符串的查找a.许多时候我们想知道某个特定的单词或短语是否在一篇文章当中我们可以运用查找解决这一问题我们以字符串在单词中的查找为例fruit banana if n in fruit: print(yes)b.讨论完字符串在不在单词之后我们的下一个目标是字符串的具体位置在哪fruit banana pos fruit.find(na) print(pos) #20、1、2第一个na在banana中2的位置所以输出2它不是在告诉你na有几个哦如果你寻找的字符不在其中则会返回-1c.接下来让我们尝试一下提取特定位置的字符data Adapting to technological advancements is crucial for seizing new opportunities and overcoming challenges begin data.find(e) print(begin) #13 stop data.find(l) print(stop) #18 run data[begin1 : stop] print(run) #chno牢记直到但不包括原则2. 字符串的变大与变小有些手机、电脑的输入法并没有英文单词首字母大写的选项我们需要不停的按CAPS LOCK来进行大小写的切换如今我们学习了Python可以运用计算机减轻我们的负担word hello world cap word.capitalize() print(cap) #Hello World我们也可以这么写print(hi there.capitalize())有大写就会有小写同时我们还有很多快捷的指令word hello world cap word.capitalize() print(cap) #Hello World mini cap.lower() print(mini) #hello world small cap.upper() print(small) #HELLO WORLD同时我们需要注意无论怎么变动world依旧是hello world没有改变3.字符的替换greet hello tom print(greet) #hello tom这是一个简单的用于打招呼的代码这是你发现你把打招呼的对象的名字弄错了但你又不想改动原代码这时你可以使用替换greet hello tom hi greet.replace(tom, jerry) print(hi) #hello jerry当然修改单个字母也是可以的greet hello tom hi greet.replace(l, i) print(hi) #heiio jerry我们把所有的l都替换成了i4.清理空格空格键很常见也很常用但是在使用中我们有可能会多打几个空格greet hello tom hi greet.lstrip() print(hi) #hello tom ola greet.rstrip() print(ola) # hello tom bonjour greet.strip() print(bonjour) #hello tomlstrip中的l是left表示删去左边的空格rstrip删去右边strip直接一步到位两边都删