如何拼接字符串? [英] How can I splice a string?

查看:36
本文介绍了如何拼接字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我可以使用数组表示法在 Python 中切片一个字符串:str[1:6],但是我如何拼接它?即,将 str[1:6] 替换为另一个可能具有不同长度的字符串?

I know I can slice a string in Python by using array notation: str[1:6], but how do I splice it? i.e., replace str[1:6] with another string, possibly of a different length?

推荐答案

没关系.认为可能有一个内置功能.改为这样写:

Nevermind. Thought there might be a built in function. Wrote this instead:

def splice(a,b,c,d=None):
    if isinstance(b,(list,tuple)):
        return a[:b[0]]+c+a[b[1]:]
    return a[:b]+d+a[c:]

>>> splice('hello world',0,5,'pizza')
'pizza world'

>>> splice('hello world',(0,5),'pizza')
'pizza world'

这篇关于如何拼接字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆