Replace a word in list and append to same list

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP











up vote
14
down vote

favorite
2












My List:



city=['Venango Municiplaity', 'Waterford ship','New York']


Expected Result:



city = ['Venango Municiplaity ', 'Waterford ship','New York','Venango','Waterford']


Common_words:



common_words = ['ship','municipality']


Scan all the items in My List and strip the common words and re-insert in the same list as shown in Expected Result.



I'm able to search the items which contains the common words but not sure how to replace that with blank and re-insert in My List.



My code so far:



for item in city:
if(any(x in s.lower() for s in item.split(' ') for x in common_words)) :






share|improve this question
















  • 1




    ... why are you splitting item and using x in s.lower() for each part of item? Provided that elements in common_words do not contain a space you can simply do if any(x in item.lower() for x in common_words). In this case maybe using regexes is simpler... you just need to do a replaced = re.sub('|'.join(map(re.escape, common_words)), item, flags=re.I) if replaced != item: city.append(replaced).
    – Giacomo Alzetta
    Aug 22 at 7:33















up vote
14
down vote

favorite
2












My List:



city=['Venango Municiplaity', 'Waterford ship','New York']


Expected Result:



city = ['Venango Municiplaity ', 'Waterford ship','New York','Venango','Waterford']


Common_words:



common_words = ['ship','municipality']


Scan all the items in My List and strip the common words and re-insert in the same list as shown in Expected Result.



I'm able to search the items which contains the common words but not sure how to replace that with blank and re-insert in My List.



My code so far:



for item in city:
if(any(x in s.lower() for s in item.split(' ') for x in common_words)) :






share|improve this question
















  • 1




    ... why are you splitting item and using x in s.lower() for each part of item? Provided that elements in common_words do not contain a space you can simply do if any(x in item.lower() for x in common_words). In this case maybe using regexes is simpler... you just need to do a replaced = re.sub('|'.join(map(re.escape, common_words)), item, flags=re.I) if replaced != item: city.append(replaced).
    – Giacomo Alzetta
    Aug 22 at 7:33













up vote
14
down vote

favorite
2









up vote
14
down vote

favorite
2






2





My List:



city=['Venango Municiplaity', 'Waterford ship','New York']


Expected Result:



city = ['Venango Municiplaity ', 'Waterford ship','New York','Venango','Waterford']


Common_words:



common_words = ['ship','municipality']


Scan all the items in My List and strip the common words and re-insert in the same list as shown in Expected Result.



I'm able to search the items which contains the common words but not sure how to replace that with blank and re-insert in My List.



My code so far:



for item in city:
if(any(x in s.lower() for s in item.split(' ') for x in common_words)) :






share|improve this question












My List:



city=['Venango Municiplaity', 'Waterford ship','New York']


Expected Result:



city = ['Venango Municiplaity ', 'Waterford ship','New York','Venango','Waterford']


Common_words:



common_words = ['ship','municipality']


Scan all the items in My List and strip the common words and re-insert in the same list as shown in Expected Result.



I'm able to search the items which contains the common words but not sure how to replace that with blank and re-insert in My List.



My code so far:



for item in city:
if(any(x in s.lower() for s in item.split(' ') for x in common_words)) :








share|improve this question











share|improve this question




share|improve this question










asked Aug 22 at 7:23









min2bro

1,83011129




1,83011129







  • 1




    ... why are you splitting item and using x in s.lower() for each part of item? Provided that elements in common_words do not contain a space you can simply do if any(x in item.lower() for x in common_words). In this case maybe using regexes is simpler... you just need to do a replaced = re.sub('|'.join(map(re.escape, common_words)), item, flags=re.I) if replaced != item: city.append(replaced).
    – Giacomo Alzetta
    Aug 22 at 7:33













  • 1




    ... why are you splitting item and using x in s.lower() for each part of item? Provided that elements in common_words do not contain a space you can simply do if any(x in item.lower() for x in common_words). In this case maybe using regexes is simpler... you just need to do a replaced = re.sub('|'.join(map(re.escape, common_words)), item, flags=re.I) if replaced != item: city.append(replaced).
    – Giacomo Alzetta
    Aug 22 at 7:33








1




1




... why are you splitting item and using x in s.lower() for each part of item? Provided that elements in common_words do not contain a space you can simply do if any(x in item.lower() for x in common_words). In this case maybe using regexes is simpler... you just need to do a replaced = re.sub('|'.join(map(re.escape, common_words)), item, flags=re.I) if replaced != item: city.append(replaced).
– Giacomo Alzetta
Aug 22 at 7:33





... why are you splitting item and using x in s.lower() for each part of item? Provided that elements in common_words do not contain a space you can simply do if any(x in item.lower() for x in common_words). In this case maybe using regexes is simpler... you just need to do a replaced = re.sub('|'.join(map(re.escape, common_words)), item, flags=re.I) if replaced != item: city.append(replaced).
– Giacomo Alzetta
Aug 22 at 7:33













8 Answers
8






active

oldest

votes

















up vote
6
down vote



accepted










I have made a small code that works as expected:



city=['Venango Municiplaity', 'Waterford ship','New York']
comwo = ['ship','municipality']
for i, c in enumerate(city):
for ii in comwo:
if ii in c:
city.append(city[i].replace(ii,""))
print(city)


Output:



['Venango Municiplaity', 'Waterford ship', 'New York', 'Waterford ']


Note:



The list you have made contains incorrect spelling.

Look at list city's first element VenangoMuniciplaity and second element of common_words municipality



Edit:



So if you also want to replace the space (if any) behind the word then I have made a separate code:



city=['Village home', 'Villagehome','New York']
comwo = ['home']
for i, c in enumerate(city):
for ii in comwo:
if ii in c:
city.append(city[i].replace(" "+ii,"")) if city[i].replace(" "+ii,"") != city[i] else city.append(city[i].replace(ii,""))
print(city)


Output:



['Village home', 'Villagehome', 'New York', 'Village', 'Village']





share|improve this answer


















  • 2




    @min2bro it replaces the words within the words as well, for example : Villageship to village. And it does not strip trailing whitespaces. And it is case-sensitive.
    – Laurent H.
    Aug 22 at 8:10











  • @LaurentH. Check the edit.
    – Black Thunder
    Aug 23 at 6:35

















up vote
6
down vote













I suggest you the following solution, using re.sub with flags=re.IGNORECASE to strip the common words ignoring the case:



import re

city = ['Venango Municipality', 'Waterford ship','New York']
common_words = ['ship','municipality']

toAppend =

for c in city:
for cw in common_words:
if cw.lower() in c.lower().split():
toAppend.append(re.sub(cw, "", c, flags=re.IGNORECASE).strip())

city += toAppend

print(city) # ['Venango Municipality', 'Waterford ship', 'New York', 'Venango', 'Waterford']


And here is the ONE-LINE STYLE solution using list comprehension, short but a bit less readable:



import re

city = ['Venango Municipality', 'Waterford ship','New York']
common_words = ['ship','municipality']

city += [re.sub(cw, "", c, flags=re.IGNORECASE).strip() for c in city for cw in common_words if cw.lower() in c.lower().split()]

print(city) # ['Venango Municipality', 'Waterford ship', 'New York', 'Venango', 'Waterford']





share|improve this answer






















  • it replace the words within the words as well, for example : Villageship to village
    – min2bro
    Aug 22 at 7:48










  • @min2bro then change if cw.lower() in c.lower(): to if cw.lower() in map(lambda x: x.lower(), c.split()): Take a look
    – Ev. Kounis
    Aug 22 at 7:53











  • You're right ! I have updated my answer with if cw.lower() in c.lower().split() instead of if cw.lower() in c.lower(). Thanks a lot.
    – Laurent H.
    Aug 22 at 8:00


















up vote
5
down vote













You can try it, create new list to save there data should be added to your original list, and then concatenate result:



In [1]: city=['Venango Municiplaity', 'Waterford ship','New York']

In [2]: common_words = ['ship', 'municiplaity']

In [3]: list_add =

In [4]: for item in city:
...: item_words = [s.lower() for s in item.split(' ')]
...: if set(common_words) & set(item_words):
...: new_item = [s for s in item.split(' ') if s.lower() not in common_words]
...: list_add.append(" ".join(new_item))
...:

In [5]: city + list_add
Out[5]: ['Venango Municiplaity', 'Waterford ship', 'New York', 'Venango', 'Waterford']





share|improve this answer



























    up vote
    4
    down vote













    This is one approach using Regex.



    Demo:



    import re

    city=['Venango Municiplaity', 'Waterford ship','New York']
    common_words = ['ship','municiplaity']
    common_words = "(" + "|".join(common_words) + ")"

    res =
    for i in city:
    if re.search(common_words, i, flags=re.IGNORECASE):
    res.append(i.strip().split()[0])
    print(city + res)


    Output:



    ['Venango Municiplaity', 'Waterford ship', 'New York', 'Venango', 'Waterford']





    share|improve this answer
















    • 1




      You should map(re.escape, common_words) to handle words containing "special characters".
      – Giacomo Alzetta
      Aug 22 at 7:36










    • if there is an item villageship, it re-inserts it, I just wanted to replace a word in the city.
      – min2bro
      Aug 22 at 7:51










    • part i.strip().split()[0] is what I am not a fan of.
      – Ev. Kounis
      Aug 22 at 7:52

















    up vote
    3
    down vote













    Put results in separate list and then use list.extend() to append contents of result list to original list



    cities = ['Venango Municipality', 'Waterford ship', 'New York']

    common_words = ['ship', 'municipality']

    add_list =

    for city in cities:
    rl =
    triggered = False
    for city_word in city.split():
    if city_word.lower() in common_words:
    triggered = True
    else:
    rl.append(city_word)
    if triggered:
    add_list.append(' '.join(rl))

    cities.extend(add_list)
    print(cities)





    share|improve this answer



























      up vote
      3
      down vote













      You can use a list comprehension in order to detect if an item contains something to add to the city list.



      city=['Venango Municipality', 'Waterford ship','New York']

      common_words = ['ship','municipality']
      items_to_add =
      for item in city:
      toAddition = [word for word in item.split() if word.lower() not in common_words]
      if ' '.join(toAddition) != item:
      items_to_add.append(' '.join(toAddition))

      print(city + items_to_add)


      Output



      ['Venango municipality', 'Waterford ship', 'New York', 'Venango', 'Waterford']





      share|improve this answer






















      • fiddling with the initial list changes the problem a bit in this case. having municipality instead of municipality makes it considerably easier.
        – Ev. Kounis
        Aug 22 at 7:43

















      up vote
      0
      down vote













      Just for fun, here's a not robust or particular efficient method



      city = ['Venango Municipality', 'Waterford ship', 'New York']
      common_words = ['ship', 'Municipality']

      city + [dict([_.split() for _ in city] + [list(reversed(_.split())) for _ in city]).get(_, '') for _ in common_words]
      >>> ['Venango Municipality', 'Waterford ship', 'New York', 'Waterford', 'Venango']





      share|improve this answer



























        up vote
        0
        down vote













        An approach with re module:



        import re

        city=['Venango Municipality', 'Waterford ship','New York']
        common_words = ['ship','municipality']
        print(city)

        for item in city:
        word_list = str(item).split(" ")
        for word in word_list:
        if word.lower() in common_words:
        word_list.remove(word)
        city.extend(word_list)
        continue

        print(city)


        output:



        ['Venango Municipality', 'Waterford ship', 'New York', 'Venango', 'Waterford']





        share|improve this answer




















          Your Answer





          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          convertImagesToLinks: true,
          noModals: false,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













           

          draft saved


          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f51961712%2freplace-a-word-in-list-and-append-to-same-list%23new-answer', 'question_page');

          );

          Post as a guest






























          8 Answers
          8






          active

          oldest

          votes








          8 Answers
          8






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          up vote
          6
          down vote



          accepted










          I have made a small code that works as expected:



          city=['Venango Municiplaity', 'Waterford ship','New York']
          comwo = ['ship','municipality']
          for i, c in enumerate(city):
          for ii in comwo:
          if ii in c:
          city.append(city[i].replace(ii,""))
          print(city)


          Output:



          ['Venango Municiplaity', 'Waterford ship', 'New York', 'Waterford ']


          Note:



          The list you have made contains incorrect spelling.

          Look at list city's first element VenangoMuniciplaity and second element of common_words municipality



          Edit:



          So if you also want to replace the space (if any) behind the word then I have made a separate code:



          city=['Village home', 'Villagehome','New York']
          comwo = ['home']
          for i, c in enumerate(city):
          for ii in comwo:
          if ii in c:
          city.append(city[i].replace(" "+ii,"")) if city[i].replace(" "+ii,"") != city[i] else city.append(city[i].replace(ii,""))
          print(city)


          Output:



          ['Village home', 'Villagehome', 'New York', 'Village', 'Village']





          share|improve this answer


















          • 2




            @min2bro it replaces the words within the words as well, for example : Villageship to village. And it does not strip trailing whitespaces. And it is case-sensitive.
            – Laurent H.
            Aug 22 at 8:10











          • @LaurentH. Check the edit.
            – Black Thunder
            Aug 23 at 6:35














          up vote
          6
          down vote



          accepted










          I have made a small code that works as expected:



          city=['Venango Municiplaity', 'Waterford ship','New York']
          comwo = ['ship','municipality']
          for i, c in enumerate(city):
          for ii in comwo:
          if ii in c:
          city.append(city[i].replace(ii,""))
          print(city)


          Output:



          ['Venango Municiplaity', 'Waterford ship', 'New York', 'Waterford ']


          Note:



          The list you have made contains incorrect spelling.

          Look at list city's first element VenangoMuniciplaity and second element of common_words municipality



          Edit:



          So if you also want to replace the space (if any) behind the word then I have made a separate code:



          city=['Village home', 'Villagehome','New York']
          comwo = ['home']
          for i, c in enumerate(city):
          for ii in comwo:
          if ii in c:
          city.append(city[i].replace(" "+ii,"")) if city[i].replace(" "+ii,"") != city[i] else city.append(city[i].replace(ii,""))
          print(city)


          Output:



          ['Village home', 'Villagehome', 'New York', 'Village', 'Village']





          share|improve this answer


















          • 2




            @min2bro it replaces the words within the words as well, for example : Villageship to village. And it does not strip trailing whitespaces. And it is case-sensitive.
            – Laurent H.
            Aug 22 at 8:10











          • @LaurentH. Check the edit.
            – Black Thunder
            Aug 23 at 6:35












          up vote
          6
          down vote



          accepted







          up vote
          6
          down vote



          accepted






          I have made a small code that works as expected:



          city=['Venango Municiplaity', 'Waterford ship','New York']
          comwo = ['ship','municipality']
          for i, c in enumerate(city):
          for ii in comwo:
          if ii in c:
          city.append(city[i].replace(ii,""))
          print(city)


          Output:



          ['Venango Municiplaity', 'Waterford ship', 'New York', 'Waterford ']


          Note:



          The list you have made contains incorrect spelling.

          Look at list city's first element VenangoMuniciplaity and second element of common_words municipality



          Edit:



          So if you also want to replace the space (if any) behind the word then I have made a separate code:



          city=['Village home', 'Villagehome','New York']
          comwo = ['home']
          for i, c in enumerate(city):
          for ii in comwo:
          if ii in c:
          city.append(city[i].replace(" "+ii,"")) if city[i].replace(" "+ii,"") != city[i] else city.append(city[i].replace(ii,""))
          print(city)


          Output:



          ['Village home', 'Villagehome', 'New York', 'Village', 'Village']





          share|improve this answer














          I have made a small code that works as expected:



          city=['Venango Municiplaity', 'Waterford ship','New York']
          comwo = ['ship','municipality']
          for i, c in enumerate(city):
          for ii in comwo:
          if ii in c:
          city.append(city[i].replace(ii,""))
          print(city)


          Output:



          ['Venango Municiplaity', 'Waterford ship', 'New York', 'Waterford ']


          Note:



          The list you have made contains incorrect spelling.

          Look at list city's first element VenangoMuniciplaity and second element of common_words municipality



          Edit:



          So if you also want to replace the space (if any) behind the word then I have made a separate code:



          city=['Village home', 'Villagehome','New York']
          comwo = ['home']
          for i, c in enumerate(city):
          for ii in comwo:
          if ii in c:
          city.append(city[i].replace(" "+ii,"")) if city[i].replace(" "+ii,"") != city[i] else city.append(city[i].replace(ii,""))
          print(city)


          Output:



          ['Village home', 'Villagehome', 'New York', 'Village', 'Village']






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Aug 30 at 9:02

























          answered Aug 22 at 7:29









          Black Thunder

          1,278425




          1,278425







          • 2




            @min2bro it replaces the words within the words as well, for example : Villageship to village. And it does not strip trailing whitespaces. And it is case-sensitive.
            – Laurent H.
            Aug 22 at 8:10











          • @LaurentH. Check the edit.
            – Black Thunder
            Aug 23 at 6:35












          • 2




            @min2bro it replaces the words within the words as well, for example : Villageship to village. And it does not strip trailing whitespaces. And it is case-sensitive.
            – Laurent H.
            Aug 22 at 8:10











          • @LaurentH. Check the edit.
            – Black Thunder
            Aug 23 at 6:35







          2




          2




          @min2bro it replaces the words within the words as well, for example : Villageship to village. And it does not strip trailing whitespaces. And it is case-sensitive.
          – Laurent H.
          Aug 22 at 8:10





          @min2bro it replaces the words within the words as well, for example : Villageship to village. And it does not strip trailing whitespaces. And it is case-sensitive.
          – Laurent H.
          Aug 22 at 8:10













          @LaurentH. Check the edit.
          – Black Thunder
          Aug 23 at 6:35




          @LaurentH. Check the edit.
          – Black Thunder
          Aug 23 at 6:35












          up vote
          6
          down vote













          I suggest you the following solution, using re.sub with flags=re.IGNORECASE to strip the common words ignoring the case:



          import re

          city = ['Venango Municipality', 'Waterford ship','New York']
          common_words = ['ship','municipality']

          toAppend =

          for c in city:
          for cw in common_words:
          if cw.lower() in c.lower().split():
          toAppend.append(re.sub(cw, "", c, flags=re.IGNORECASE).strip())

          city += toAppend

          print(city) # ['Venango Municipality', 'Waterford ship', 'New York', 'Venango', 'Waterford']


          And here is the ONE-LINE STYLE solution using list comprehension, short but a bit less readable:



          import re

          city = ['Venango Municipality', 'Waterford ship','New York']
          common_words = ['ship','municipality']

          city += [re.sub(cw, "", c, flags=re.IGNORECASE).strip() for c in city for cw in common_words if cw.lower() in c.lower().split()]

          print(city) # ['Venango Municipality', 'Waterford ship', 'New York', 'Venango', 'Waterford']





          share|improve this answer






















          • it replace the words within the words as well, for example : Villageship to village
            – min2bro
            Aug 22 at 7:48










          • @min2bro then change if cw.lower() in c.lower(): to if cw.lower() in map(lambda x: x.lower(), c.split()): Take a look
            – Ev. Kounis
            Aug 22 at 7:53











          • You're right ! I have updated my answer with if cw.lower() in c.lower().split() instead of if cw.lower() in c.lower(). Thanks a lot.
            – Laurent H.
            Aug 22 at 8:00















          up vote
          6
          down vote













          I suggest you the following solution, using re.sub with flags=re.IGNORECASE to strip the common words ignoring the case:



          import re

          city = ['Venango Municipality', 'Waterford ship','New York']
          common_words = ['ship','municipality']

          toAppend =

          for c in city:
          for cw in common_words:
          if cw.lower() in c.lower().split():
          toAppend.append(re.sub(cw, "", c, flags=re.IGNORECASE).strip())

          city += toAppend

          print(city) # ['Venango Municipality', 'Waterford ship', 'New York', 'Venango', 'Waterford']


          And here is the ONE-LINE STYLE solution using list comprehension, short but a bit less readable:



          import re

          city = ['Venango Municipality', 'Waterford ship','New York']
          common_words = ['ship','municipality']

          city += [re.sub(cw, "", c, flags=re.IGNORECASE).strip() for c in city for cw in common_words if cw.lower() in c.lower().split()]

          print(city) # ['Venango Municipality', 'Waterford ship', 'New York', 'Venango', 'Waterford']





          share|improve this answer






















          • it replace the words within the words as well, for example : Villageship to village
            – min2bro
            Aug 22 at 7:48










          • @min2bro then change if cw.lower() in c.lower(): to if cw.lower() in map(lambda x: x.lower(), c.split()): Take a look
            – Ev. Kounis
            Aug 22 at 7:53











          • You're right ! I have updated my answer with if cw.lower() in c.lower().split() instead of if cw.lower() in c.lower(). Thanks a lot.
            – Laurent H.
            Aug 22 at 8:00













          up vote
          6
          down vote










          up vote
          6
          down vote









          I suggest you the following solution, using re.sub with flags=re.IGNORECASE to strip the common words ignoring the case:



          import re

          city = ['Venango Municipality', 'Waterford ship','New York']
          common_words = ['ship','municipality']

          toAppend =

          for c in city:
          for cw in common_words:
          if cw.lower() in c.lower().split():
          toAppend.append(re.sub(cw, "", c, flags=re.IGNORECASE).strip())

          city += toAppend

          print(city) # ['Venango Municipality', 'Waterford ship', 'New York', 'Venango', 'Waterford']


          And here is the ONE-LINE STYLE solution using list comprehension, short but a bit less readable:



          import re

          city = ['Venango Municipality', 'Waterford ship','New York']
          common_words = ['ship','municipality']

          city += [re.sub(cw, "", c, flags=re.IGNORECASE).strip() for c in city for cw in common_words if cw.lower() in c.lower().split()]

          print(city) # ['Venango Municipality', 'Waterford ship', 'New York', 'Venango', 'Waterford']





          share|improve this answer














          I suggest you the following solution, using re.sub with flags=re.IGNORECASE to strip the common words ignoring the case:



          import re

          city = ['Venango Municipality', 'Waterford ship','New York']
          common_words = ['ship','municipality']

          toAppend =

          for c in city:
          for cw in common_words:
          if cw.lower() in c.lower().split():
          toAppend.append(re.sub(cw, "", c, flags=re.IGNORECASE).strip())

          city += toAppend

          print(city) # ['Venango Municipality', 'Waterford ship', 'New York', 'Venango', 'Waterford']


          And here is the ONE-LINE STYLE solution using list comprehension, short but a bit less readable:



          import re

          city = ['Venango Municipality', 'Waterford ship','New York']
          common_words = ['ship','municipality']

          city += [re.sub(cw, "", c, flags=re.IGNORECASE).strip() for c in city for cw in common_words if cw.lower() in c.lower().split()]

          print(city) # ['Venango Municipality', 'Waterford ship', 'New York', 'Venango', 'Waterford']






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Aug 22 at 8:17

























          answered Aug 22 at 7:40









          Laurent H.

          3,7411530




          3,7411530











          • it replace the words within the words as well, for example : Villageship to village
            – min2bro
            Aug 22 at 7:48










          • @min2bro then change if cw.lower() in c.lower(): to if cw.lower() in map(lambda x: x.lower(), c.split()): Take a look
            – Ev. Kounis
            Aug 22 at 7:53











          • You're right ! I have updated my answer with if cw.lower() in c.lower().split() instead of if cw.lower() in c.lower(). Thanks a lot.
            – Laurent H.
            Aug 22 at 8:00

















          • it replace the words within the words as well, for example : Villageship to village
            – min2bro
            Aug 22 at 7:48










          • @min2bro then change if cw.lower() in c.lower(): to if cw.lower() in map(lambda x: x.lower(), c.split()): Take a look
            – Ev. Kounis
            Aug 22 at 7:53











          • You're right ! I have updated my answer with if cw.lower() in c.lower().split() instead of if cw.lower() in c.lower(). Thanks a lot.
            – Laurent H.
            Aug 22 at 8:00
















          it replace the words within the words as well, for example : Villageship to village
          – min2bro
          Aug 22 at 7:48




          it replace the words within the words as well, for example : Villageship to village
          – min2bro
          Aug 22 at 7:48












          @min2bro then change if cw.lower() in c.lower(): to if cw.lower() in map(lambda x: x.lower(), c.split()): Take a look
          – Ev. Kounis
          Aug 22 at 7:53





          @min2bro then change if cw.lower() in c.lower(): to if cw.lower() in map(lambda x: x.lower(), c.split()): Take a look
          – Ev. Kounis
          Aug 22 at 7:53













          You're right ! I have updated my answer with if cw.lower() in c.lower().split() instead of if cw.lower() in c.lower(). Thanks a lot.
          – Laurent H.
          Aug 22 at 8:00





          You're right ! I have updated my answer with if cw.lower() in c.lower().split() instead of if cw.lower() in c.lower(). Thanks a lot.
          – Laurent H.
          Aug 22 at 8:00











          up vote
          5
          down vote













          You can try it, create new list to save there data should be added to your original list, and then concatenate result:



          In [1]: city=['Venango Municiplaity', 'Waterford ship','New York']

          In [2]: common_words = ['ship', 'municiplaity']

          In [3]: list_add =

          In [4]: for item in city:
          ...: item_words = [s.lower() for s in item.split(' ')]
          ...: if set(common_words) & set(item_words):
          ...: new_item = [s for s in item.split(' ') if s.lower() not in common_words]
          ...: list_add.append(" ".join(new_item))
          ...:

          In [5]: city + list_add
          Out[5]: ['Venango Municiplaity', 'Waterford ship', 'New York', 'Venango', 'Waterford']





          share|improve this answer
























            up vote
            5
            down vote













            You can try it, create new list to save there data should be added to your original list, and then concatenate result:



            In [1]: city=['Venango Municiplaity', 'Waterford ship','New York']

            In [2]: common_words = ['ship', 'municiplaity']

            In [3]: list_add =

            In [4]: for item in city:
            ...: item_words = [s.lower() for s in item.split(' ')]
            ...: if set(common_words) & set(item_words):
            ...: new_item = [s for s in item.split(' ') if s.lower() not in common_words]
            ...: list_add.append(" ".join(new_item))
            ...:

            In [5]: city + list_add
            Out[5]: ['Venango Municiplaity', 'Waterford ship', 'New York', 'Venango', 'Waterford']





            share|improve this answer






















              up vote
              5
              down vote










              up vote
              5
              down vote









              You can try it, create new list to save there data should be added to your original list, and then concatenate result:



              In [1]: city=['Venango Municiplaity', 'Waterford ship','New York']

              In [2]: common_words = ['ship', 'municiplaity']

              In [3]: list_add =

              In [4]: for item in city:
              ...: item_words = [s.lower() for s in item.split(' ')]
              ...: if set(common_words) & set(item_words):
              ...: new_item = [s for s in item.split(' ') if s.lower() not in common_words]
              ...: list_add.append(" ".join(new_item))
              ...:

              In [5]: city + list_add
              Out[5]: ['Venango Municiplaity', 'Waterford ship', 'New York', 'Venango', 'Waterford']





              share|improve this answer












              You can try it, create new list to save there data should be added to your original list, and then concatenate result:



              In [1]: city=['Venango Municiplaity', 'Waterford ship','New York']

              In [2]: common_words = ['ship', 'municiplaity']

              In [3]: list_add =

              In [4]: for item in city:
              ...: item_words = [s.lower() for s in item.split(' ')]
              ...: if set(common_words) & set(item_words):
              ...: new_item = [s for s in item.split(' ') if s.lower() not in common_words]
              ...: list_add.append(" ".join(new_item))
              ...:

              In [5]: city + list_add
              Out[5]: ['Venango Municiplaity', 'Waterford ship', 'New York', 'Venango', 'Waterford']






              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Aug 22 at 7:36









              Bear Brown

              11k81637




              11k81637




















                  up vote
                  4
                  down vote













                  This is one approach using Regex.



                  Demo:



                  import re

                  city=['Venango Municiplaity', 'Waterford ship','New York']
                  common_words = ['ship','municiplaity']
                  common_words = "(" + "|".join(common_words) + ")"

                  res =
                  for i in city:
                  if re.search(common_words, i, flags=re.IGNORECASE):
                  res.append(i.strip().split()[0])
                  print(city + res)


                  Output:



                  ['Venango Municiplaity', 'Waterford ship', 'New York', 'Venango', 'Waterford']





                  share|improve this answer
















                  • 1




                    You should map(re.escape, common_words) to handle words containing "special characters".
                    – Giacomo Alzetta
                    Aug 22 at 7:36










                  • if there is an item villageship, it re-inserts it, I just wanted to replace a word in the city.
                    – min2bro
                    Aug 22 at 7:51










                  • part i.strip().split()[0] is what I am not a fan of.
                    – Ev. Kounis
                    Aug 22 at 7:52














                  up vote
                  4
                  down vote













                  This is one approach using Regex.



                  Demo:



                  import re

                  city=['Venango Municiplaity', 'Waterford ship','New York']
                  common_words = ['ship','municiplaity']
                  common_words = "(" + "|".join(common_words) + ")"

                  res =
                  for i in city:
                  if re.search(common_words, i, flags=re.IGNORECASE):
                  res.append(i.strip().split()[0])
                  print(city + res)


                  Output:



                  ['Venango Municiplaity', 'Waterford ship', 'New York', 'Venango', 'Waterford']





                  share|improve this answer
















                  • 1




                    You should map(re.escape, common_words) to handle words containing "special characters".
                    – Giacomo Alzetta
                    Aug 22 at 7:36










                  • if there is an item villageship, it re-inserts it, I just wanted to replace a word in the city.
                    – min2bro
                    Aug 22 at 7:51










                  • part i.strip().split()[0] is what I am not a fan of.
                    – Ev. Kounis
                    Aug 22 at 7:52












                  up vote
                  4
                  down vote










                  up vote
                  4
                  down vote









                  This is one approach using Regex.



                  Demo:



                  import re

                  city=['Venango Municiplaity', 'Waterford ship','New York']
                  common_words = ['ship','municiplaity']
                  common_words = "(" + "|".join(common_words) + ")"

                  res =
                  for i in city:
                  if re.search(common_words, i, flags=re.IGNORECASE):
                  res.append(i.strip().split()[0])
                  print(city + res)


                  Output:



                  ['Venango Municiplaity', 'Waterford ship', 'New York', 'Venango', 'Waterford']





                  share|improve this answer












                  This is one approach using Regex.



                  Demo:



                  import re

                  city=['Venango Municiplaity', 'Waterford ship','New York']
                  common_words = ['ship','municiplaity']
                  common_words = "(" + "|".join(common_words) + ")"

                  res =
                  for i in city:
                  if re.search(common_words, i, flags=re.IGNORECASE):
                  res.append(i.strip().split()[0])
                  print(city + res)


                  Output:



                  ['Venango Municiplaity', 'Waterford ship', 'New York', 'Venango', 'Waterford']






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Aug 22 at 7:35









                  Rakesh

                  32.7k103568




                  32.7k103568







                  • 1




                    You should map(re.escape, common_words) to handle words containing "special characters".
                    – Giacomo Alzetta
                    Aug 22 at 7:36










                  • if there is an item villageship, it re-inserts it, I just wanted to replace a word in the city.
                    – min2bro
                    Aug 22 at 7:51










                  • part i.strip().split()[0] is what I am not a fan of.
                    – Ev. Kounis
                    Aug 22 at 7:52












                  • 1




                    You should map(re.escape, common_words) to handle words containing "special characters".
                    – Giacomo Alzetta
                    Aug 22 at 7:36










                  • if there is an item villageship, it re-inserts it, I just wanted to replace a word in the city.
                    – min2bro
                    Aug 22 at 7:51










                  • part i.strip().split()[0] is what I am not a fan of.
                    – Ev. Kounis
                    Aug 22 at 7:52







                  1




                  1




                  You should map(re.escape, common_words) to handle words containing "special characters".
                  – Giacomo Alzetta
                  Aug 22 at 7:36




                  You should map(re.escape, common_words) to handle words containing "special characters".
                  – Giacomo Alzetta
                  Aug 22 at 7:36












                  if there is an item villageship, it re-inserts it, I just wanted to replace a word in the city.
                  – min2bro
                  Aug 22 at 7:51




                  if there is an item villageship, it re-inserts it, I just wanted to replace a word in the city.
                  – min2bro
                  Aug 22 at 7:51












                  part i.strip().split()[0] is what I am not a fan of.
                  – Ev. Kounis
                  Aug 22 at 7:52




                  part i.strip().split()[0] is what I am not a fan of.
                  – Ev. Kounis
                  Aug 22 at 7:52










                  up vote
                  3
                  down vote













                  Put results in separate list and then use list.extend() to append contents of result list to original list



                  cities = ['Venango Municipality', 'Waterford ship', 'New York']

                  common_words = ['ship', 'municipality']

                  add_list =

                  for city in cities:
                  rl =
                  triggered = False
                  for city_word in city.split():
                  if city_word.lower() in common_words:
                  triggered = True
                  else:
                  rl.append(city_word)
                  if triggered:
                  add_list.append(' '.join(rl))

                  cities.extend(add_list)
                  print(cities)





                  share|improve this answer
























                    up vote
                    3
                    down vote













                    Put results in separate list and then use list.extend() to append contents of result list to original list



                    cities = ['Venango Municipality', 'Waterford ship', 'New York']

                    common_words = ['ship', 'municipality']

                    add_list =

                    for city in cities:
                    rl =
                    triggered = False
                    for city_word in city.split():
                    if city_word.lower() in common_words:
                    triggered = True
                    else:
                    rl.append(city_word)
                    if triggered:
                    add_list.append(' '.join(rl))

                    cities.extend(add_list)
                    print(cities)





                    share|improve this answer






















                      up vote
                      3
                      down vote










                      up vote
                      3
                      down vote









                      Put results in separate list and then use list.extend() to append contents of result list to original list



                      cities = ['Venango Municipality', 'Waterford ship', 'New York']

                      common_words = ['ship', 'municipality']

                      add_list =

                      for city in cities:
                      rl =
                      triggered = False
                      for city_word in city.split():
                      if city_word.lower() in common_words:
                      triggered = True
                      else:
                      rl.append(city_word)
                      if triggered:
                      add_list.append(' '.join(rl))

                      cities.extend(add_list)
                      print(cities)





                      share|improve this answer












                      Put results in separate list and then use list.extend() to append contents of result list to original list



                      cities = ['Venango Municipality', 'Waterford ship', 'New York']

                      common_words = ['ship', 'municipality']

                      add_list =

                      for city in cities:
                      rl =
                      triggered = False
                      for city_word in city.split():
                      if city_word.lower() in common_words:
                      triggered = True
                      else:
                      rl.append(city_word)
                      if triggered:
                      add_list.append(' '.join(rl))

                      cities.extend(add_list)
                      print(cities)






                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Aug 22 at 7:41









                      leotrubach

                      1,03669




                      1,03669




















                          up vote
                          3
                          down vote













                          You can use a list comprehension in order to detect if an item contains something to add to the city list.



                          city=['Venango Municipality', 'Waterford ship','New York']

                          common_words = ['ship','municipality']
                          items_to_add =
                          for item in city:
                          toAddition = [word for word in item.split() if word.lower() not in common_words]
                          if ' '.join(toAddition) != item:
                          items_to_add.append(' '.join(toAddition))

                          print(city + items_to_add)


                          Output



                          ['Venango municipality', 'Waterford ship', 'New York', 'Venango', 'Waterford']





                          share|improve this answer






















                          • fiddling with the initial list changes the problem a bit in this case. having municipality instead of municipality makes it considerably easier.
                            – Ev. Kounis
                            Aug 22 at 7:43














                          up vote
                          3
                          down vote













                          You can use a list comprehension in order to detect if an item contains something to add to the city list.



                          city=['Venango Municipality', 'Waterford ship','New York']

                          common_words = ['ship','municipality']
                          items_to_add =
                          for item in city:
                          toAddition = [word for word in item.split() if word.lower() not in common_words]
                          if ' '.join(toAddition) != item:
                          items_to_add.append(' '.join(toAddition))

                          print(city + items_to_add)


                          Output



                          ['Venango municipality', 'Waterford ship', 'New York', 'Venango', 'Waterford']





                          share|improve this answer






















                          • fiddling with the initial list changes the problem a bit in this case. having municipality instead of municipality makes it considerably easier.
                            – Ev. Kounis
                            Aug 22 at 7:43












                          up vote
                          3
                          down vote










                          up vote
                          3
                          down vote









                          You can use a list comprehension in order to detect if an item contains something to add to the city list.



                          city=['Venango Municipality', 'Waterford ship','New York']

                          common_words = ['ship','municipality']
                          items_to_add =
                          for item in city:
                          toAddition = [word for word in item.split() if word.lower() not in common_words]
                          if ' '.join(toAddition) != item:
                          items_to_add.append(' '.join(toAddition))

                          print(city + items_to_add)


                          Output



                          ['Venango municipality', 'Waterford ship', 'New York', 'Venango', 'Waterford']





                          share|improve this answer














                          You can use a list comprehension in order to detect if an item contains something to add to the city list.



                          city=['Venango Municipality', 'Waterford ship','New York']

                          common_words = ['ship','municipality']
                          items_to_add =
                          for item in city:
                          toAddition = [word for word in item.split() if word.lower() not in common_words]
                          if ' '.join(toAddition) != item:
                          items_to_add.append(' '.join(toAddition))

                          print(city + items_to_add)


                          Output



                          ['Venango municipality', 'Waterford ship', 'New York', 'Venango', 'Waterford']






                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited Aug 22 at 7:45

























                          answered Aug 22 at 7:40









                          Mihai Alexandru-Ionut

                          27.4k63363




                          27.4k63363











                          • fiddling with the initial list changes the problem a bit in this case. having municipality instead of municipality makes it considerably easier.
                            – Ev. Kounis
                            Aug 22 at 7:43
















                          • fiddling with the initial list changes the problem a bit in this case. having municipality instead of municipality makes it considerably easier.
                            – Ev. Kounis
                            Aug 22 at 7:43















                          fiddling with the initial list changes the problem a bit in this case. having municipality instead of municipality makes it considerably easier.
                          – Ev. Kounis
                          Aug 22 at 7:43




                          fiddling with the initial list changes the problem a bit in this case. having municipality instead of municipality makes it considerably easier.
                          – Ev. Kounis
                          Aug 22 at 7:43










                          up vote
                          0
                          down vote













                          Just for fun, here's a not robust or particular efficient method



                          city = ['Venango Municipality', 'Waterford ship', 'New York']
                          common_words = ['ship', 'Municipality']

                          city + [dict([_.split() for _ in city] + [list(reversed(_.split())) for _ in city]).get(_, '') for _ in common_words]
                          >>> ['Venango Municipality', 'Waterford ship', 'New York', 'Waterford', 'Venango']





                          share|improve this answer
























                            up vote
                            0
                            down vote













                            Just for fun, here's a not robust or particular efficient method



                            city = ['Venango Municipality', 'Waterford ship', 'New York']
                            common_words = ['ship', 'Municipality']

                            city + [dict([_.split() for _ in city] + [list(reversed(_.split())) for _ in city]).get(_, '') for _ in common_words]
                            >>> ['Venango Municipality', 'Waterford ship', 'New York', 'Waterford', 'Venango']





                            share|improve this answer






















                              up vote
                              0
                              down vote










                              up vote
                              0
                              down vote









                              Just for fun, here's a not robust or particular efficient method



                              city = ['Venango Municipality', 'Waterford ship', 'New York']
                              common_words = ['ship', 'Municipality']

                              city + [dict([_.split() for _ in city] + [list(reversed(_.split())) for _ in city]).get(_, '') for _ in common_words]
                              >>> ['Venango Municipality', 'Waterford ship', 'New York', 'Waterford', 'Venango']





                              share|improve this answer












                              Just for fun, here's a not robust or particular efficient method



                              city = ['Venango Municipality', 'Waterford ship', 'New York']
                              common_words = ['ship', 'Municipality']

                              city + [dict([_.split() for _ in city] + [list(reversed(_.split())) for _ in city]).get(_, '') for _ in common_words]
                              >>> ['Venango Municipality', 'Waterford ship', 'New York', 'Waterford', 'Venango']






                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered Aug 22 at 15:56









                              bphi

                              2,13511021




                              2,13511021




















                                  up vote
                                  0
                                  down vote













                                  An approach with re module:



                                  import re

                                  city=['Venango Municipality', 'Waterford ship','New York']
                                  common_words = ['ship','municipality']
                                  print(city)

                                  for item in city:
                                  word_list = str(item).split(" ")
                                  for word in word_list:
                                  if word.lower() in common_words:
                                  word_list.remove(word)
                                  city.extend(word_list)
                                  continue

                                  print(city)


                                  output:



                                  ['Venango Municipality', 'Waterford ship', 'New York', 'Venango', 'Waterford']





                                  share|improve this answer
























                                    up vote
                                    0
                                    down vote













                                    An approach with re module:



                                    import re

                                    city=['Venango Municipality', 'Waterford ship','New York']
                                    common_words = ['ship','municipality']
                                    print(city)

                                    for item in city:
                                    word_list = str(item).split(" ")
                                    for word in word_list:
                                    if word.lower() in common_words:
                                    word_list.remove(word)
                                    city.extend(word_list)
                                    continue

                                    print(city)


                                    output:



                                    ['Venango Municipality', 'Waterford ship', 'New York', 'Venango', 'Waterford']





                                    share|improve this answer






















                                      up vote
                                      0
                                      down vote










                                      up vote
                                      0
                                      down vote









                                      An approach with re module:



                                      import re

                                      city=['Venango Municipality', 'Waterford ship','New York']
                                      common_words = ['ship','municipality']
                                      print(city)

                                      for item in city:
                                      word_list = str(item).split(" ")
                                      for word in word_list:
                                      if word.lower() in common_words:
                                      word_list.remove(word)
                                      city.extend(word_list)
                                      continue

                                      print(city)


                                      output:



                                      ['Venango Municipality', 'Waterford ship', 'New York', 'Venango', 'Waterford']





                                      share|improve this answer












                                      An approach with re module:



                                      import re

                                      city=['Venango Municipality', 'Waterford ship','New York']
                                      common_words = ['ship','municipality']
                                      print(city)

                                      for item in city:
                                      word_list = str(item).split(" ")
                                      for word in word_list:
                                      if word.lower() in common_words:
                                      word_list.remove(word)
                                      city.extend(word_list)
                                      continue

                                      print(city)


                                      output:



                                      ['Venango Municipality', 'Waterford ship', 'New York', 'Venango', 'Waterford']






                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered Aug 28 at 9:41









                                      josephzhong

                                      11




                                      11



























                                           

                                          draft saved


                                          draft discarded















































                                           


                                          draft saved


                                          draft discarded














                                          StackExchange.ready(
                                          function ()
                                          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f51961712%2freplace-a-word-in-list-and-append-to-same-list%23new-answer', 'question_page');

                                          );

                                          Post as a guest













































































                                          Comments

                                          Popular posts from this blog

                                          What does second last employer means? [closed]

                                          List of Gilmore Girls characters

                                          Confectionery