字符串操作补充

1.字符串的查找

       a.许多时候我们想知道某个特定的单词或短语是否在一篇文章当中,我们可以运用查找解决这一问题,我们以字符串在单词中的查找为例

fruit = 'banana'

if 'n' in fruit:

    print('yes')    

        b.讨论完字符串在不在单词之后,我们的下一个目标是字符串的具体位置在哪

fruit = 'banana'

pos = fruit.find('na')

print(pos)    #2

0、1、2第一个na在banana中2的位置,所以输出2,它不是在告诉你na有几个哦,如果你寻找的字符不在其中,则会返回-1

        c.接下来让我们尝试一下提取特定位置的字符

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[begin+1 : 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都替换成了i

4.清理空格

        空格键很常见也很常用,但是在使用中,我们有可能会多打几个空格

greet = '            hello            tom          '

hi = greet.lstrip()

print(hi)    #hello            tom          

ola = greet.rstrip()

print(ola)    #            hello            tom

bonjour = greet.strip()

print(bonjour)    #hello            tom

lstrip中的l是left,表示删去左边的空格,rstrip删去右边,strip直接一步到位两边都删

你可能感兴趣的:(前端)