How can I splice a string?

前端 未结 5 1584
独厮守ぢ
独厮守ぢ 2020-12-17 14:30

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 anot

相关标签:
5条回答
  • 2020-12-17 15:04

    Strings are immutable in Python. The best you can do is construct a new string:

    t = s[:1] + "whatever" + s[6:]
    
    0 讨论(0)
  • 2020-12-17 15:08

    You can't do this since strings in Python are immutable.

    Try next:

    new_s = ''.join((s[:1], new, s[6:]))
    
    0 讨论(0)
  • 2020-12-17 15:11

    Python strings are immutable, you need to manually:

    new = str[:1] + new + str[6:]
    
    0 讨论(0)
  • 2020-12-17 15:16

    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'
    
    0 讨论(0)
  • 2020-12-17 15:22

    What about such try?

    >>> str = 'This is something...'
    >>> s = 'Theese are'
    >>> print str
    This is something...
    >>> str = str.replace(str[0:7], s)
    >>> print str
    Theese are something...
    
    0 讨论(0)
提交回复
热议问题