-8
a = "hello world, hello there, hello python"

How do you change only the middle "hello" to let's say "hi"? Thanks in advance! EDIT: I want to change the only the middle hello even if the string is 'hi world, hello there, hello python', in which case the target "hello" is the first occurrence whereas in the first case it is the second

psycoxer
  • 151
  • 13
  • Is `a.replace("hello there", "hi there")` acceptable or are you thinking more generally how to replace the middle element in a string? – Kent Shikama Dec 17 '19 at 05:30
  • yes looking of a more general way and only to replace "hello" – psycoxer Dec 17 '19 at 05:38
  • Does this answer your question? [How to find and replace nth occurrence of word in a sentence using python regular expression?](https://stackoverflow.com/questions/27589325/how-to-find-and-replace-nth-occurrence-of-word-in-a-sentence-using-python-regula) – Dishin H Goyani Dec 17 '19 at 05:40
  • I don't know whether it will be the 1st or the 2nd occurrence of the substring(the input could vary) so I donk know the value of n for each line to replace the nth term. – psycoxer Dec 17 '19 at 06:27

5 Answers5

1

I am not sure how general you want things to be. Check this if it meets your requirement:

def replace_middle(target, replacement, string):
    list_a = string.split()
    target_ids = [i for i, word in enumerate(list_a) if word == target]
    middle_elem = target_ids[len(target_ids)//2]
    list_a[middle_elem] = replacement
    print(' '.join(list_a))

a = "hello world, hello there, hello python"
replace_middle('hello', 'hi', a)

Output:

hello world, hi there, hello python
Sayandip Dutta
  • 15,602
  • 4
  • 23
  • 52
  • So i have checked your code and it is more time complex and taking more time to execute. As there is no need of loop to solve the problem. And also you can edit it to make it generic by not only replacing middle but nth word. – Akhil Pathania Dec 17 '19 at 06:49
  • I agree with everything you said. But I did not want to use `re`. Without `re` you do need loop. And the OP asked for the middle one, not `N`th. – Sayandip Dutta Dec 17 '19 at 06:51
  • So directly you can use a.replace("hello","hi",2).replace("hi","hello",1). I have checked this also and time is 0.295. Or else index = a.find("hello",2) a = a[:index] + a[index:].replace("hello","hi",1) time nearly 0.4. This will not use re. also more fast. Thanks – Akhil Pathania Dec 17 '19 at 06:53
  • You are focusing on this particular example alone. If there are more occurrences, it will fail without a loop. – Sayandip Dutta Dec 17 '19 at 06:55
  • No, I guess you are correct. – Sayandip Dutta Dec 17 '19 at 06:58
  • We just need to play with the occurrence and finding which we can use a var and take input in it. – Akhil Pathania Dec 17 '19 at 06:59
  • Yes, it does work. But the problem with replace is, instead of `hello` if there is `othello` it will replace it to `othi` – Sayandip Dutta Dec 17 '19 at 07:01
  • Yes that case will come if there is something appended to the 2nd hello. – Akhil Pathania Dec 17 '19 at 07:05
1

with respect to clarification you should ask your question in more specific way. without a good explanation there is no way to answer your question. but because your new I will answer you as what I understood from what you said.

import re

def replaceTheNTH(str, substr, substitute, N)
    wh = [m.start() for m in re.finditer(substr, str)][N-1]
    before = str[:wh]

    after = str[wh:]
    after = aft.replace(substr, substitute, 1)
    newString = before + after
    print newString

Calling this method will help you. you can replace the n occurrence of a substr in a larger string. for your case you can call this

replaceTheNTH(a,'hello','hi',2)
0

This should work just fine:

a = "hello world, hi there, hello python"

Replacing the whole string is fast, easy to write and easy to understand.


Let's assume, someone asks how to replace:

"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."

with

"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"

Anyone wants to recommend using re, string manipulation or something fancy?

lenik
  • 23,228
  • 4
  • 34
  • 43
0

I just got a trick for you to achieving what you want.

a = "hello world, hello there, hello python"
a = a.replace("hello","hi",2).replace("hi","hello",1)
print(a)

So what exactly 2nd Line does it it is replacing first two occurrence of hello to hi and then replacing 1st occurrence of hi to hello. Thus getting the output you want.

Or you can also go to other way as follows:

a = "hello world, hello there, hello python"
index = a.find("hello",2)    
a = a[:index] + a[index:].replace("hello","hi",1)
print(a)

So you can use any of them for your purpose.

Akhil Pathania
  • 542
  • 2
  • 5
  • 19
-1

Although strings are immutable(cannot change them), we can still manipulate them:

a = a[:13] + "hi" + a[18:]
Kavan Doctor
  • 187
  • 5
  • 3
    This not a solution. You need to specify how did you find that 13 and 18 value. What if its not hello but hey. This will fail. Edit i would suggest is to use the find function to get the index. – Akhil Pathania Dec 17 '19 at 06:56