9

I mean, i want to replace str[9:11] for another string. If I do str.replace(str[9:11], "###") It doesn't work, because the sequence [9:11] can be more than one time. If str is "cdabcjkewabcef" i would get "cd###jkew###ef" but I only want to replace the second.

Morgan Thrapp
10k3 gold badges51 silver badges68 bronze badges
asked Aug 9, 2016 at 16:36
1
  • 1
    Using 'string.replace' converts every occurrence of the given text to the text you input. You are not wanting to do this, you just want to replace the text based on its position (index), not based on its contents. Commented Aug 9, 2016 at 17:37

6 Answers 6

18

you can do

s="cdabcjkewabcef"
snew="".join((s[:9],"###",s[12:]))

which should be faster than joining like snew=s[:9]+"###"+s[12:] on large strings

answered Aug 9, 2016 at 16:57
Sign up to request clarification or add additional context in comments.

Comments

3

You can achieve this by doing:

yourString = "Hello"
yourIndexToReplace = 1 #e letter
newLetter = 'x'
yourStringNew="".join((yourString[:yourIndexToReplace],newLetter,yourString[yourIndexToReplace+1:]))
answered May 28, 2017 at 18:40

Comments

2

You can use join() with sub-strings.

s = 'cdabcjkewabcef'
sequence = '###'
indicies = (9,11)
print sequence.join([s[:indicies[0]-1], s[indicies[1]:]])
>>> 'cdabcjke###cef'
answered Aug 9, 2016 at 16:52

Comments

1

Given txt and s - the string you want to replace:

txt.replace(s, "***", 1).replace(s, "###").replace("***", s)

Another way:

txt[::-1].replace(s[::-1], "###", 1)[::-1]
answered Aug 9, 2016 at 16:45

Comments

1
str = "cdabcjkewabcef"
print((str[::-1].replace('cba','###',1))[::-1])
Dharman
34k27 gold badges106 silver badges158 bronze badges
answered May 2, 2020 at 16:11

1 Comment

This would be a better answer if you explained how the code you provided answers the question.
0

Here is a sample code:

word = "astalavista"
index = 0
newword = ""
addon = "xyz"
while index < 8:
 newword = newword + word[index]
 index += 1
 ind = index
i = 0
while i < len(addon):
 newword = newword + addon[i]
 i += 1
while ind < len(word):
 newword = newword + word[ind]
 ind += 1
print newword
answered Aug 9, 2016 at 16:51

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.