replace() | 字符串的替换,返回一个新的字符串,不会改变原有的字符串。 |
join() | 字符串的拼接,将列表或者元组中的字符串合并成一个字符串。 |
1、replace() 字符串的替换
1)语法
str_name.replace(old_str, new_str[, count])
使用新子串 new_str 去替换旧子串 old_str,第三个参数指的是最大替换次数,省略的话,最大替换次数就是子串出现的次数。若指定的最大替换次数大于子串出现次数,则按照子串出现的次数执行。
2)实例
s = 'hello,python,hello,python'
print(s.replace('python','Java')) #hello,Java,hello,Java
str1 = 'hello,python and java and python ands php'
str2 = str1.replace('and','he') #最大替换次数默认为子串'and'出现的次数
str3 = str1.replace('o','8',1) #1是最大替换次
print(str1,id(str1)) #hello,python and java and python ands php 2808735217296
print(str2,id(str2)) #hello,python he java he python hes php 2808735218736
print(str3,id(str3)) #hell8,python and java and python ands php 2509070208432
2、join() 字符串的拼接
1) 语法
str_name.join(多字符串组成的序列) ------- str_name是连接符号,将序列中的每个字符串连接起来,可以为空
str_name 表示的是连接符号,将序列中的每个字符串连接起来,可以为空。
2)实例
join() 将列表或者元组中的字符串合并成一个字符串。
lst = ['a','b','c','d']
lst1 = ''.join(lst)
print(lst,id(lst)) # ['a', 'b', 'c', 'd'] 2044655949312
print(lst1,id(lst1)) # abcd 2044659418416
# 输出:a66b66c66d
lst2 = '66'.join(lst)
print(lst2,id(lst2)) # a66b66c66d 2490411627120
myTuple = ('hello','python','java','php')
# 输出:hello_python_java_php
t1 = '_'.join(myTuple)
print(t1,id(t1)) # hello_python_java_php 2770175096064
# 把字符串'python'作为了字符串序列去进行连接
print('*'.join('python')) # p*y*t*h*o*n
还可以使用格式化字符串的方式去拼接字符串。
© 版权声明
本站网络名称:
尤尤博客
本站永久网址:
https://www.yxfseo.cn
网站侵权说明:
本网站的文章部分内容可能来源于网络,仅供大家学习与参考,请在24H内删除。
1 本站一切资源不代表本站立场,并不代表本站赞同其观点和对其真实性负责。
2 本站一律禁止以任何方式发布或转载任何违法的相关信息,访客发现请向站长举报。
3 本站资源大多存储在云盘,如发现链接失效,请联系我们我们会第一时间更新。
1 本站一切资源不代表本站立场,并不代表本站赞同其观点和对其真实性负责。
2 本站一律禁止以任何方式发布或转载任何违法的相关信息,访客发现请向站长举报。
3 本站资源大多存储在云盘,如发现链接失效,请联系我们我们会第一时间更新。
THE END
暂无评论内容