Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You could just make a nice little looping function.</p> <pre><code>def replace_all(text, dic): for i, j in dic.iteritems(): text = text.replace(i, j) return text </code></pre> <p>where <code>text</code> is the complete string and <code>dic</code> is a dictionary &mdash; each definition is a string that will replace a match to the term.</p> <p><strong>Note</strong>: in Python 3, <code>iteritems()</code> has been replaced with <code>items()</code></p> <hr> <p><strong>Careful:</strong> Python dictionaries don't have a reliable order for iteration. This solution only solves your problem if: </p> <ul> <li>order of replacements is irrelevant</li> <li>it's ok for a replacement to change the results of previous replacements</li> </ul> <p>For instance:</p> <pre><code>d = { "cat": "dog", "dog": "pig"} mySentence = "This is my cat and this is my dog." replace_all(mySentence, d) print(mySentence) </code></pre> <p>Possible output #1:</p> <pre>"This is my pig and this is my pig."</pre> <p>Possible output #2</p> <pre>"This is my dog and this is my pig."</pre> <p>One possible fix is to use an OrderedDict.</p> <pre><code>from collections import OrderedDict def replace_all(text, dic): for i, j in dic.items(): text = text.replace(i, j) return text od = OrderedDict([("cat", "dog"), ("dog", "pig")]) mySentence = "This is my cat and this is my dog." replace_all(mySentence, od) print(mySentence) </code></pre> <p>Output:</p> <pre><code>"This is my pig and this is my pig." </code></pre> <hr> <p><strong>Careful #2:</strong> Inefficient if your <code>text</code> string is too big or there are many pairs in the dictionary.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload