Python中字符串的拼接和替换操作

字符串是不可变序列,在对其进行修改时,会产生新的字符串对象,而原有的字符串不变:

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
图片[1]-Python中字符串的拼接和替换操作-尤尤'blog

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
图片[2]-Python中字符串的拼接和替换操作-尤尤'blog

还可以使用格式化字符串的方式去拼接字符串。

© 版权声明
THE END
喜欢就支持一下吧
点赞10 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容