Python String Handling

subhabangalore at gmail.com subhabangalore at gmail.com
Sat Nov 12 03:46:58 EST 2016


On Saturday, November 12, 2016 at 7:34:31 AM UTC+5:30, Steve D'Aprano wrote:
> On Sat, 12 Nov 2016 09:29 am wrote:
> 
> > I have a string
> > "Hello my name is Richard"
> > 
> > I have a list of words as,
> > ['Hello/Hi','my','name','is','Richard/P']
> > 
> > I want to identify the match of 'Hello' and 'Richard'
> > in list, and replace them with 'Hello/Hi" and 'Richard/P'
> > respectively.
> > 
> > The result should look like,
> > "Hello/Hi my name is Richard/P".
> 
> Looks like you want:
> 
> 
> mystring = "Hello my name is Richard"
> words = ['Hello/Hi', 'my', 'name', 'is', 'Richard/P']
> result = " ".join(words)
> 
> assert result == "Hello/Hi my name is Richard/P"
> 
> 
> and mystring is irrelevant.
> 
> 
> 
> 
> -- 
> Steve
> “Cheer up,” they said, “things could be worse.” So I cheered up, and sure
> enough, things got worse.

Thank you all for your kind time. 
The problem is slightly more complex.

I am restating the problem. 

"Hello my name is Richard"

is a string. 

I have tagged the words Hello and Richard
as "Hello/Hi" and "Richard/P". 
After this I could get the string as a list of words
as in,
['Hello/Hi','my','name','is','Richard/P'] 

Now I want to replace the string with 
Hello/Hi my name is Richard/P

It may seem a joining of list but is not because
if I try to make, 
['Hello/Hi','my/M','name','is/I','Richard/P'] 

I may do, but doing the following string 

Hello/Hi my/M<HM> name is/I Richard/P<IP>

is tough as entities with tag may vary. I have to make
a rule. 

I am trying to recognize the index of the word in
the list, pop it and replace with new value and joining
the list as string.

This is okay but as expert people if you have any smarter
suggestion.

Thanks in advance

 





More information about the Python-list mailing list