Character Translation using Python (like the tr command)












36















Is there a way to do character translation (kind of like the tr command) using python










share|improve this question























  • For a Perl guy, calling it translation — as opposed to transliteration — made finding the right thing to do a bit more complicated.

    – Trenton
    Oct 16 '18 at 17:36
















36















Is there a way to do character translation (kind of like the tr command) using python










share|improve this question























  • For a Perl guy, calling it translation — as opposed to transliteration — made finding the right thing to do a bit more complicated.

    – Trenton
    Oct 16 '18 at 17:36














36












36








36


2






Is there a way to do character translation (kind of like the tr command) using python










share|improve this question














Is there a way to do character translation (kind of like the tr command) using python







python






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Feb 17 '09 at 6:33









hhafezhhafez

21.2k32104137




21.2k32104137













  • For a Perl guy, calling it translation — as opposed to transliteration — made finding the right thing to do a bit more complicated.

    – Trenton
    Oct 16 '18 at 17:36



















  • For a Perl guy, calling it translation — as opposed to transliteration — made finding the right thing to do a bit more complicated.

    – Trenton
    Oct 16 '18 at 17:36

















For a Perl guy, calling it translation — as opposed to transliteration — made finding the right thing to do a bit more complicated.

– Trenton
Oct 16 '18 at 17:36





For a Perl guy, calling it translation — as opposed to transliteration — made finding the right thing to do a bit more complicated.

– Trenton
Oct 16 '18 at 17:36












5 Answers
5






active

oldest

votes


















37














See string.translate



import string
"abc".translate(string.maketrans("abc", "def")) # => "def"


Note the doc's comments about subtleties in the translation of unicode strings.



Edit: Since tr is a bit more advanced, also consider using re.sub.






share|improve this answer





















  • 8





    For python3, 'module' object has no attribute 'maketrans'. Use "abc".translate(str.maketrans("abc", "def")) directly!

    – SparkAndShine
    Jul 18 '15 at 23:58





















20














If you're using python3 translate is less verbose:



>>> 'abc'.translate(str.maketrans('ac','xy'))
'xby'


Ahh.. and there is also equivalent to tr -d:



>>> "abc".translate(str.maketrans('','','b'))
'ac'


For tr -d with python2.x use an additional argument to translate function:



>>> "abc".translate(None, 'b')
'ac'





share|improve this answer





















  • 1





    is there an equivalent for tr -cd?

    – Sundeep
    Jun 27 '16 at 8:50



















5














I has developed python-tr, implemented tr algorithm.
Let's try it.



Install:



$ pip install python-tr


Example:



>>> from tr import tr
>>> tr('bn', 'cr', 'bunny')
'curry'
>>> tr('n', '', 'bunny', 'd')
'buy'
>>> tr('n', 'u', 'bunny', 'c')
'uunnu'
>>> tr('n', '', 'bunny', 's')
'buny'
>>> tr('bn', '', 'bunny', 'cd')
'bnn'
>>> tr('bn', 'cr', 'bunny', 'cs')
'brnnr'
>>> tr('bn', 'cr', 'bunny', 'ds')
'uy'



  • https://pypi.python.org/pypi/python-tr

  • https://github.com/ikegami-yukino/python-tr






share|improve this answer































    1














    In Python 2, unicode.translate() accepts ordinary mappings, ie. there's no need to import anything either:



    >>> u'abc+-'.translate({ord('+'): u'-', ord('-'): u'+', ord('b'): None})
    u'ac-+'


    The translate() method is especially useful for swapping characters (as '+' and '-' above), which can't be done with replace(), and using re.sub() isn't very straightforward for that purpose either.



    I have to admit, however, that the repeated use of ord() doesn't make the code look like nice and tidy.






    share|improve this answer































      -4














      A simpler approach may be to use replace. e.g.



       "abc".replace("abc", "def")
      'def'


      No need to import anything. Works in Python 2.x






      share|improve this answer



















      • 5





        it works in Python 3 as well but doesn't do what the OP is asking for.

        – iruvar
        Oct 3 '13 at 18:02






      • 1





        the translation cb to wt should transform cabbage to wattage

        – Jasen
        Sep 25 '15 at 1:14













      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',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      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%2f555705%2fcharacter-translation-using-python-like-the-tr-command%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      5 Answers
      5






      active

      oldest

      votes








      5 Answers
      5






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      37














      See string.translate



      import string
      "abc".translate(string.maketrans("abc", "def")) # => "def"


      Note the doc's comments about subtleties in the translation of unicode strings.



      Edit: Since tr is a bit more advanced, also consider using re.sub.






      share|improve this answer





















      • 8





        For python3, 'module' object has no attribute 'maketrans'. Use "abc".translate(str.maketrans("abc", "def")) directly!

        – SparkAndShine
        Jul 18 '15 at 23:58


















      37














      See string.translate



      import string
      "abc".translate(string.maketrans("abc", "def")) # => "def"


      Note the doc's comments about subtleties in the translation of unicode strings.



      Edit: Since tr is a bit more advanced, also consider using re.sub.






      share|improve this answer





















      • 8





        For python3, 'module' object has no attribute 'maketrans'. Use "abc".translate(str.maketrans("abc", "def")) directly!

        – SparkAndShine
        Jul 18 '15 at 23:58
















      37












      37








      37







      See string.translate



      import string
      "abc".translate(string.maketrans("abc", "def")) # => "def"


      Note the doc's comments about subtleties in the translation of unicode strings.



      Edit: Since tr is a bit more advanced, also consider using re.sub.






      share|improve this answer















      See string.translate



      import string
      "abc".translate(string.maketrans("abc", "def")) # => "def"


      Note the doc's comments about subtleties in the translation of unicode strings.



      Edit: Since tr is a bit more advanced, also consider using re.sub.







      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited May 12 '12 at 10:21









      robert

      22.9k84668




      22.9k84668










      answered Feb 17 '09 at 6:40









      Richard LevasseurRichard Levasseur

      9,87854155




      9,87854155








      • 8





        For python3, 'module' object has no attribute 'maketrans'. Use "abc".translate(str.maketrans("abc", "def")) directly!

        – SparkAndShine
        Jul 18 '15 at 23:58
















      • 8





        For python3, 'module' object has no attribute 'maketrans'. Use "abc".translate(str.maketrans("abc", "def")) directly!

        – SparkAndShine
        Jul 18 '15 at 23:58










      8




      8





      For python3, 'module' object has no attribute 'maketrans'. Use "abc".translate(str.maketrans("abc", "def")) directly!

      – SparkAndShine
      Jul 18 '15 at 23:58







      For python3, 'module' object has no attribute 'maketrans'. Use "abc".translate(str.maketrans("abc", "def")) directly!

      – SparkAndShine
      Jul 18 '15 at 23:58















      20














      If you're using python3 translate is less verbose:



      >>> 'abc'.translate(str.maketrans('ac','xy'))
      'xby'


      Ahh.. and there is also equivalent to tr -d:



      >>> "abc".translate(str.maketrans('','','b'))
      'ac'


      For tr -d with python2.x use an additional argument to translate function:



      >>> "abc".translate(None, 'b')
      'ac'





      share|improve this answer





















      • 1





        is there an equivalent for tr -cd?

        – Sundeep
        Jun 27 '16 at 8:50
















      20














      If you're using python3 translate is less verbose:



      >>> 'abc'.translate(str.maketrans('ac','xy'))
      'xby'


      Ahh.. and there is also equivalent to tr -d:



      >>> "abc".translate(str.maketrans('','','b'))
      'ac'


      For tr -d with python2.x use an additional argument to translate function:



      >>> "abc".translate(None, 'b')
      'ac'





      share|improve this answer





















      • 1





        is there an equivalent for tr -cd?

        – Sundeep
        Jun 27 '16 at 8:50














      20












      20








      20







      If you're using python3 translate is less verbose:



      >>> 'abc'.translate(str.maketrans('ac','xy'))
      'xby'


      Ahh.. and there is also equivalent to tr -d:



      >>> "abc".translate(str.maketrans('','','b'))
      'ac'


      For tr -d with python2.x use an additional argument to translate function:



      >>> "abc".translate(None, 'b')
      'ac'





      share|improve this answer















      If you're using python3 translate is less verbose:



      >>> 'abc'.translate(str.maketrans('ac','xy'))
      'xby'


      Ahh.. and there is also equivalent to tr -d:



      >>> "abc".translate(str.maketrans('','','b'))
      'ac'


      For tr -d with python2.x use an additional argument to translate function:



      >>> "abc".translate(None, 'b')
      'ac'






      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Sep 12 '16 at 22:29









      Telemachus

      16.6k64778




      16.6k64778










      answered Sep 6 '09 at 12:17









      Piotr CzaplaPiotr Czapla

      14.5k2177105




      14.5k2177105








      • 1





        is there an equivalent for tr -cd?

        – Sundeep
        Jun 27 '16 at 8:50














      • 1





        is there an equivalent for tr -cd?

        – Sundeep
        Jun 27 '16 at 8:50








      1




      1





      is there an equivalent for tr -cd?

      – Sundeep
      Jun 27 '16 at 8:50





      is there an equivalent for tr -cd?

      – Sundeep
      Jun 27 '16 at 8:50











      5














      I has developed python-tr, implemented tr algorithm.
      Let's try it.



      Install:



      $ pip install python-tr


      Example:



      >>> from tr import tr
      >>> tr('bn', 'cr', 'bunny')
      'curry'
      >>> tr('n', '', 'bunny', 'd')
      'buy'
      >>> tr('n', 'u', 'bunny', 'c')
      'uunnu'
      >>> tr('n', '', 'bunny', 's')
      'buny'
      >>> tr('bn', '', 'bunny', 'cd')
      'bnn'
      >>> tr('bn', 'cr', 'bunny', 'cs')
      'brnnr'
      >>> tr('bn', 'cr', 'bunny', 'ds')
      'uy'



      • https://pypi.python.org/pypi/python-tr

      • https://github.com/ikegami-yukino/python-tr






      share|improve this answer




























        5














        I has developed python-tr, implemented tr algorithm.
        Let's try it.



        Install:



        $ pip install python-tr


        Example:



        >>> from tr import tr
        >>> tr('bn', 'cr', 'bunny')
        'curry'
        >>> tr('n', '', 'bunny', 'd')
        'buy'
        >>> tr('n', 'u', 'bunny', 'c')
        'uunnu'
        >>> tr('n', '', 'bunny', 's')
        'buny'
        >>> tr('bn', '', 'bunny', 'cd')
        'bnn'
        >>> tr('bn', 'cr', 'bunny', 'cs')
        'brnnr'
        >>> tr('bn', 'cr', 'bunny', 'ds')
        'uy'



        • https://pypi.python.org/pypi/python-tr

        • https://github.com/ikegami-yukino/python-tr






        share|improve this answer


























          5












          5








          5







          I has developed python-tr, implemented tr algorithm.
          Let's try it.



          Install:



          $ pip install python-tr


          Example:



          >>> from tr import tr
          >>> tr('bn', 'cr', 'bunny')
          'curry'
          >>> tr('n', '', 'bunny', 'd')
          'buy'
          >>> tr('n', 'u', 'bunny', 'c')
          'uunnu'
          >>> tr('n', '', 'bunny', 's')
          'buny'
          >>> tr('bn', '', 'bunny', 'cd')
          'bnn'
          >>> tr('bn', 'cr', 'bunny', 'cs')
          'brnnr'
          >>> tr('bn', 'cr', 'bunny', 'ds')
          'uy'



          • https://pypi.python.org/pypi/python-tr

          • https://github.com/ikegami-yukino/python-tr






          share|improve this answer













          I has developed python-tr, implemented tr algorithm.
          Let's try it.



          Install:



          $ pip install python-tr


          Example:



          >>> from tr import tr
          >>> tr('bn', 'cr', 'bunny')
          'curry'
          >>> tr('n', '', 'bunny', 'd')
          'buy'
          >>> tr('n', 'u', 'bunny', 'c')
          'uunnu'
          >>> tr('n', '', 'bunny', 's')
          'buny'
          >>> tr('bn', '', 'bunny', 'cd')
          'bnn'
          >>> tr('bn', 'cr', 'bunny', 'cs')
          'brnnr'
          >>> tr('bn', 'cr', 'bunny', 'ds')
          'uy'



          • https://pypi.python.org/pypi/python-tr

          • https://github.com/ikegami-yukino/python-tr







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Jan 15 '15 at 13:11









          Yukino IkegamiYukino Ikegami

          8214




          8214























              1














              In Python 2, unicode.translate() accepts ordinary mappings, ie. there's no need to import anything either:



              >>> u'abc+-'.translate({ord('+'): u'-', ord('-'): u'+', ord('b'): None})
              u'ac-+'


              The translate() method is especially useful for swapping characters (as '+' and '-' above), which can't be done with replace(), and using re.sub() isn't very straightforward for that purpose either.



              I have to admit, however, that the repeated use of ord() doesn't make the code look like nice and tidy.






              share|improve this answer




























                1














                In Python 2, unicode.translate() accepts ordinary mappings, ie. there's no need to import anything either:



                >>> u'abc+-'.translate({ord('+'): u'-', ord('-'): u'+', ord('b'): None})
                u'ac-+'


                The translate() method is especially useful for swapping characters (as '+' and '-' above), which can't be done with replace(), and using re.sub() isn't very straightforward for that purpose either.



                I have to admit, however, that the repeated use of ord() doesn't make the code look like nice and tidy.






                share|improve this answer


























                  1












                  1








                  1







                  In Python 2, unicode.translate() accepts ordinary mappings, ie. there's no need to import anything either:



                  >>> u'abc+-'.translate({ord('+'): u'-', ord('-'): u'+', ord('b'): None})
                  u'ac-+'


                  The translate() method is especially useful for swapping characters (as '+' and '-' above), which can't be done with replace(), and using re.sub() isn't very straightforward for that purpose either.



                  I have to admit, however, that the repeated use of ord() doesn't make the code look like nice and tidy.






                  share|improve this answer













                  In Python 2, unicode.translate() accepts ordinary mappings, ie. there's no need to import anything either:



                  >>> u'abc+-'.translate({ord('+'): u'-', ord('-'): u'+', ord('b'): None})
                  u'ac-+'


                  The translate() method is especially useful for swapping characters (as '+' and '-' above), which can't be done with replace(), and using re.sub() isn't very straightforward for that purpose either.



                  I have to admit, however, that the repeated use of ord() doesn't make the code look like nice and tidy.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Apr 18 '14 at 17:41









                  lenzlenz

                  3,04441832




                  3,04441832























                      -4














                      A simpler approach may be to use replace. e.g.



                       "abc".replace("abc", "def")
                      'def'


                      No need to import anything. Works in Python 2.x






                      share|improve this answer



















                      • 5





                        it works in Python 3 as well but doesn't do what the OP is asking for.

                        – iruvar
                        Oct 3 '13 at 18:02






                      • 1





                        the translation cb to wt should transform cabbage to wattage

                        – Jasen
                        Sep 25 '15 at 1:14


















                      -4














                      A simpler approach may be to use replace. e.g.



                       "abc".replace("abc", "def")
                      'def'


                      No need to import anything. Works in Python 2.x






                      share|improve this answer



















                      • 5





                        it works in Python 3 as well but doesn't do what the OP is asking for.

                        – iruvar
                        Oct 3 '13 at 18:02






                      • 1





                        the translation cb to wt should transform cabbage to wattage

                        – Jasen
                        Sep 25 '15 at 1:14
















                      -4












                      -4








                      -4







                      A simpler approach may be to use replace. e.g.



                       "abc".replace("abc", "def")
                      'def'


                      No need to import anything. Works in Python 2.x






                      share|improve this answer













                      A simpler approach may be to use replace. e.g.



                       "abc".replace("abc", "def")
                      'def'


                      No need to import anything. Works in Python 2.x







                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Oct 3 '13 at 18:00









                      Chris HaagChris Haag

                      1




                      1








                      • 5





                        it works in Python 3 as well but doesn't do what the OP is asking for.

                        – iruvar
                        Oct 3 '13 at 18:02






                      • 1





                        the translation cb to wt should transform cabbage to wattage

                        – Jasen
                        Sep 25 '15 at 1:14
















                      • 5





                        it works in Python 3 as well but doesn't do what the OP is asking for.

                        – iruvar
                        Oct 3 '13 at 18:02






                      • 1





                        the translation cb to wt should transform cabbage to wattage

                        – Jasen
                        Sep 25 '15 at 1:14










                      5




                      5





                      it works in Python 3 as well but doesn't do what the OP is asking for.

                      – iruvar
                      Oct 3 '13 at 18:02





                      it works in Python 3 as well but doesn't do what the OP is asking for.

                      – iruvar
                      Oct 3 '13 at 18:02




                      1




                      1





                      the translation cb to wt should transform cabbage to wattage

                      – Jasen
                      Sep 25 '15 at 1:14







                      the translation cb to wt should transform cabbage to wattage

                      – Jasen
                      Sep 25 '15 at 1:14




















                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f555705%2fcharacter-translation-using-python-like-the-tr-command%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Xamarin.iOS Cant Deploy on Iphone

                      Glorious Revolution

                      Dulmage-Mendelsohn matrix decomposition in Python