-9

I want to replace part of a string in Python. In particular, I want to get rid of the structure "Hello[hi, ... ,bye]", where the dots represent any length of characters.

I have found that in How to use string.replace() in python 3.x it is explained how to use replace, but I can not figure out how to match the pattern "Hello[hi, ... ,bye]" with an arbitrary piece of string in place of '...'

Example 1:

text= "Hello.hi[. Hello[hi, my name is alice ,bye] ,bye]"

I want: result= "Hello.hi[., 123 my name is alice 456 ,bye]"

But I want the same pattern also to work for example 2:

text= "Hello.hi[., Hello[hi, have a good day ,bye] ,bye]"

I want: result= "Hello.hi[., 123 have a good day 456 ,bye]"

Any suggestions? Thanks.

yago
  • 1
  • 1
  • 3
  • 3
    Possible duplicate of [How to use string.replace() in python 3.x](https://stackoverflow.com/questions/9452108/how-to-use-string-replace-in-python-3-x) – Mentos Aug 14 '17 at 13:24

3 Answers3

0

Use replace.

text= "Hello[hi, my name is alice ,bye] "
text.replace('hi,', '123').replace(',bye', '456')
>>> 'Hello[123 my name is alice 456] '

Same would work for "Hello[hi, have a good day ,bye] "

Artur Barseghyan
  • 12,746
  • 4
  • 52
  • 44
  • You don't replace enough. It should be: `text.replace('Hello[hi,', '123').replace(',bye] ', '456')` – Matthias Aug 14 '17 at 13:27
  • Hi, thanks for the answer! I have already tried that, but I don't get what I want. I have edited the post to make the problem more clear. – yago Aug 14 '17 at 13:51
  • @yago: I see. You should absolutely be using `regex` (`import re`) search/replace then. See the manuals on the internet for using it with Python. – Artur Barseghyan Aug 14 '17 at 13:56
  • @Artur Barseghyan,Thanks! yes, I have been reading about regex, but I am a beginner and I could not solved it yet, so I posted here in case anyone could illuminate me. I will keep reading though. Thanks again. – yago Aug 14 '17 at 14:01
  • @yago: Do you only want to replace words within the opening and closing brackets? Otherwise, please, make your question very specific. – Artur Barseghyan Aug 14 '17 at 14:08
0

Try this,

index_l=[]
x=0
for i in text:
    if i == ',':index_l.append(i)
output = text[index_l[0]:index_l[1]]
print output
Ubdus Samad
  • 1,218
  • 1
  • 15
  • 27
0

Thanks to all. I have solved the problem using this post Python: Replace string with prefixStringSuffix keeping original case, but ignoring case when searching for match

Solution

import re
text="Hello[hi, my name is alice ,bye]"
search = re.compile(r'Hello\[hi,(.*?),bye\]')
a=search.sub('123\\1 456', text)
print(a)
yago
  • 1
  • 1
  • 3