【Python】在字符串指定位置插入字符串

 字符串插入函数:

# 在字符串指定位置插入字符
# str_origin:源字符串  pos:插入位置  str_add:待插入的字符串
#
def str_insert(str_origin, pos, str_add):
    str_list = list(str_origin)    # 字符串转list
    str_list.insert(pos, str_add)  # 在指定位置插入字符串
    str_out = ''.join(str_list)    # 空字符连接
    return  str_out

 

说明:

在Python中,字符串是不可变的,而列表是可变的。字符串无法直接删除、插入字符串之间的特定字符,所以将字符串转变为列表,就可以实现对字符串中特定字符的操作。


.insert()用法--插入字符

 L.insert(index, object) -- insert object before index

注意:.insert()方法不返回参数,直接在对L进行修改。属于列表的方法。

**将对象插入到指定位置的前面。比如['a', 'b'].insert(1, 'c'),那么最后的输出就是`[‘a’, ‘c’, ‘b’]。 **

 

.join()方法--连接字符

S.join(iterable) -> str 
    Return a string which is the concatenation of the strings in the
    iterable.  The separator between elements is S.

a.join(b),比如 b=123456,是可以迭代的。这个方法的作用就是把a插入到b中每个字符中。1a2a3a4a5a6就是输出。
''.join([a, b])是比较常见的用法。''是空字符,意味着在a, b之间加入空字符,即将a, b进行连接。

 

参考

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值