侧边栏壁纸
  • 累计撰写 119 篇文章
  • 累计创建 25 个标签
  • 累计收到 1 条评论

目 录CONTENT

文章目录

字符串操作之修改

梁来福
2022-02-01 / 0 评论 / 0 点赞 / 4 阅读 / 1350 字
温馨提示:
本文最后更新于 2024-05-06,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。
str = 'hello world and hello python and hello java'

1、replace() ---替换函数

语法:字符串序列.replace(旧子串,新子串, 替换次数)

1.1 将‘and’替换为‘和’

new_str = str.replace('and', '和')
print(new_str)

执行结果:hello world 和 hello python 和 hello java

1.2 将‘and’替换为‘和’一次

new_str = str.replace('and', '和', 1)
print(new_str)

执行结果:hello world 和 hello python and hello java

总结:

调用了replace函数后发现原字符串的数据并没有修改,修改后的数据是replace函数的返回值;

说明字符串是不可变数据类型;


2、split() ---分割函数,返回一个列表,丢失分割字符

语法:字符串序列.split(分割字符, num)

注意:num表示分割字符出现的次数,即分割几次,将来返回数据个数为num+1个

2.1 以‘and’为分割符分割str

new_str1 = str.split('and')
print(new_str1)

执行结果:['hello world ', ' hello python ', ' hello java']

2.2 以‘and’为分割符分割str一次

new_str1 = str.split('and', 1)
print(new_str1)

执行结果:['hello world ', ' hello python and hello java']


3、join() ---合并函数,合并列表里的字符串数据为一个大字符串

语法:字符或子串.join(多字符串组成的序列)

list = ['aa', 'bb', 'cc']

将list里的字符串用符号‘=’连接

new_str = '='.join(list)

执行结果:aa=bb=cc

0
  1. 支付宝打赏

    qrcode alipay
  2. 微信打赏

    qrcode weixin
博主关闭了所有页面的评论