How can I splice a string?

Question:

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?

Asked By: mpen

||

Answers:

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

Try next:

new_s = ''.join((s[:1], new, s[6:]))
Answered By: Roman Bodnarchuk

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

t = s[:1] + "whatever" + s[6:]
Answered By: Sven Marnach

Python strings are immutable, you need to manually:

new = str[:1] + new + str[6:]
Answered By: xyz-123

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'
Answered By: mpen

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...
Answered By: tony

For a more "JavaScript compliant" string splice:

def splice(target, start, delete_count='', insert=''):
    """
    >>> splice('hello pizza world', 6, 5, 'pasta')
    ('hello pasta world', 'pizza')

    >>> s = 'hello pizza world'
    >>> s, food = splice(s, (6, 5), 'pasta')
    >>> s, food
    ('hello pasta world', 'pizza')
    """
    if isinstance(start, (list, tuple)):
        insert = delete_count
        start, delete_count = start
    delete_count += start
    return target[:start] + insert + target[delete_count:], target[start:delete_count]

Note that because string arguments are immutable in Python, it is necessary to return two parameters: the modified string, and the removed text.

Answered By: Orwellophile
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.