0

I'm trying to overwrite a string with another string (from an index), in Python 3.x. I want to know if there is already a String method that can already do this or if there is an efficient way to do this.

I know the easiest way to achieve this would be to write a loop that starts at an index and then replaces each character of string a with string b (shown in code below).

def func(a, b, index):
    newStr = list(a)
    for i in range(index, index+len(b)):
        if i < len(a):
            newStr[i] = b[i-index]
        else:
            newStr.append(b[i-index])
    return ''.join(newStr)

If I have two strings string: a = '012345678' and b = 'abcde'

And the index set as 6, then the expected output from the function should be: '012345abcde'.

2
  • do you know slicing? a[:6] + b Commented Aug 18, 2019 at 9:53
  • Note that strings in Python are immutable. You cannot overwrite them. But you can combine (parts of) strings into a new string, which is what skymon's answer does. Commented Aug 18, 2019 at 9:58

1 Answer 1

2

You could do:

def func(a, b, index):
    return a[:index] + b
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.