Python string.translate() Examples

The following are 30 code examples for showing how to use string.translate(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module string , or try the search function .

Example 1
Project: bugatsinho.github.io   Author: bugatsinho   File: sport365.py    License: GNU General Public License v3.0 6 votes vote down vote up
def derot(xset, hset, src):
    xset = eval(xset)
    hset = eval(hset)

    import string
    o = ''
    u = ''
    il = 0
    for first in hset:
        u += first
        o += xset[il]
        il += 1
    rot13 = string.maketrans(o, u)
    link = string.translate(src, rot13)
    xbmc.log('@#@DEROT-LINK: %s' % link, xbmc.LOGNOTICE)
    return link 
Example 2
Project: BinderFilter   Author: dxwu   File: install.py    License: MIT License 6 votes vote down vote up
def dump_dirs (self, msg):
        if DEBUG:
            from distutils.fancy_getopt import longopt_xlate
            print msg + ":"
            for opt in self.user_options:
                opt_name = opt[0]
                if opt_name[-1] == "=":
                    opt_name = opt_name[0:-1]
                if opt_name in self.negative_opt:
                    opt_name = string.translate(self.negative_opt[opt_name],
                                                longopt_xlate)
                    val = not getattr(self, opt_name)
                else:
                    opt_name = string.translate(opt_name, longopt_xlate)
                    val = getattr(self, opt_name)
                print "  %s: %s" % (opt_name, val) 
Example 3
Project: featherduster   Author: nccgroup   File: helpers.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def do_simple_substitution(ciphertext, pt_charset, ct_charset):
   '''
   Perform simple substitution based on character sets

   Simplifies the use of string.translate(). If, for instance, you wish to
   transform a ciphertext where 'e' is swapped with 't', you would call this
   function like so:

   do_simple_substitution('Simplt subeieueion ciphtrs art silly','et','te')
   
   ciphertext - A string to translate
   pt_charset - The character set of the plaintext, usually 'abcdefghijk...xyz'
   ct_charset - The character set of the ciphertext
   '''
   #translate ciphertext to plaintext using mapping
   return string.translate(ciphertext, string.maketrans(ct_charset, pt_charset))


# TODO: Implement chi square 
Example 4
Project: featherduster   Author: nccgroup   File: classical.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def morse_decode(text, dot='.', dash='-', space=' '):
   '''
   Decodes a Morse encoded message. Optionally, you can provide an alternate
   single character for dot, dash, and space.

   Parameters:
   text - (string) A message to decode
   dot - (char) An alternate dot char
   dash - (char) An alternate dash char
   space - (char) A char to split the text on
   '''
   inverse_morse_table = map(lambda (x,y): (y,x), morse_table.items())
   dot_dash_trans = string.maketrans('.-', dot+dash)
   inverse_morse_table = [(string.translate(x,dot_dash_trans), y) for (x,y) in inverse_morse_table]
   inverse_morse_table = dict(inverse_morse_table)
   return ''.join([inverse_morse_table[char] for char in text.split(space) if char in inverse_morse_table.keys()]) 
Example 5
Project: addon   Author: alfa-addon   File: subtitletools.py    License: GNU General Public License v3.0 6 votes vote down vote up
def _normalize(title, charset='utf-8'):
    '''Removes all accents and illegal chars for titles from the String'''
    if isinstance(title, unicode):
        title = string.translate(title, allchars, deletechars)
        try:
            title = title.encode("utf-8")
            title = normalize('NFKD', title).encode('ASCII', 'ignore')
        except UnicodeEncodeError:
            logger.error("Error de encoding")
    else:
        title = string.translate(title, allchars, deletechars)
        try:
            # iso-8859-1
            title = title.decode(charset).encode('utf-8')
            title = normalize('NFKD', unicode(title, 'utf-8'))
            title = title.encode('ASCII', 'ignore')
        except UnicodeEncodeError:
            logger.error("Error de encoding")
    return title

    # 
Example 6
Project: Arya   Author: HarmJ0y   File: arya.py    License: GNU General Public License v3.0 5 votes vote down vote up
def b64sub(s, key):
    """
    "Encryption" method that base64 encodes a given string, 
    then does a randomized alphabetic letter substitution.
    """
    enc_tbl = string.maketrans(string.ascii_letters, key)
    return string.translate(base64.b64encode(s), enc_tbl) 
Example 7
Project: neverendshadowsocks   Author: ntfreedom   File: table.py    License: Apache License 2.0 5 votes vote down vote up
def update(self, data):
        if self._op:
            return translate(data, self._encrypt_table)
        else:
            return translate(data, self._decrypt_table) 
Example 8
Project: python-netsurv   Author: sofia-netsurv   File: unittest_checker_python3.py    License: MIT License 5 votes vote down vote up
def test_bad_str_translate_call_string_literal(self):
        node = astroid.extract_node(
            """
         foobar.translate(None, 'abc123') #@
         """
        )
        message = testutils.Message(
            "deprecated-str-translate-call", node=node, confidence=INFERENCE_FAILURE
        )
        with self.assertAddsMessages(message):
            self.checker.visit_call(node) 
Example 9
Project: python-netsurv   Author: sofia-netsurv   File: unittest_checker_python3.py    License: MIT License 5 votes vote down vote up
def test_bad_str_translate_call_variable(self):
        node = astroid.extract_node(
            """
         def raz(foobar):
           foobar.translate(None, 'hello') #@
         """
        )
        message = testutils.Message(
            "deprecated-str-translate-call", node=node, confidence=INFERENCE_FAILURE
        )
        with self.assertAddsMessages(message):
            self.checker.visit_call(node) 
Example 10
Project: python-netsurv   Author: sofia-netsurv   File: unittest_checker_python3.py    License: MIT License 5 votes vote down vote up
def test_bad_str_translate_call_infer_str(self):
        node = astroid.extract_node(
            """
         foobar = "hello world"
         foobar.translate(None, foobar) #@
         """
        )
        message = testutils.Message(
            "deprecated-str-translate-call", node=node, confidence=INFERENCE
        )
        with self.assertAddsMessages(message):
            self.checker.visit_call(node) 
Example 11
Project: python-netsurv   Author: sofia-netsurv   File: unittest_checker_python3.py    License: MIT License 5 votes vote down vote up
def test_ok_str_translate_call_integer(self):
        node = astroid.extract_node(
            """
         foobar.translate(None, 33) #@
         """
        )
        with self.assertNoMessages():
            self.checker.visit_call(node) 
Example 12
Project: python-netsurv   Author: sofia-netsurv   File: unittest_checker_python3.py    License: MIT License 5 votes vote down vote up
def test_ok_str_translate_call_keyword(self):
        node = astroid.extract_node(
            """
         foobar.translate(None, 'foobar', raz=33) #@
         """
        )
        with self.assertNoMessages():
            self.checker.visit_call(node) 
Example 13
Project: python-netsurv   Author: sofia-netsurv   File: unittest_checker_python3.py    License: MIT License 5 votes vote down vote up
def test_six_ifexp_conditional(self):
        code = """
        from __future__ import absolute_import
        import six
        import string
        string.translate if six.PY2 else None
        """
        module = astroid.parse(code)
        with self.assertNoMessages():
            self.walk(module) 
Example 14
Project: python-netsurv   Author: sofia-netsurv   File: unittest_checker_python3.py    License: MIT License 5 votes vote down vote up
def test_bad_str_translate_call_string_literal(self):
        node = astroid.extract_node(
            """
         foobar.translate(None, 'abc123') #@
         """
        )
        message = testutils.Message(
            "deprecated-str-translate-call", node=node, confidence=INFERENCE_FAILURE
        )
        with self.assertAddsMessages(message):
            self.checker.visit_call(node) 
Example 15
Project: python-netsurv   Author: sofia-netsurv   File: unittest_checker_python3.py    License: MIT License 5 votes vote down vote up
def test_bad_str_translate_call_variable(self):
        node = astroid.extract_node(
            """
         def raz(foobar):
           foobar.translate(None, 'hello') #@
         """
        )
        message = testutils.Message(
            "deprecated-str-translate-call", node=node, confidence=INFERENCE_FAILURE
        )
        with self.assertAddsMessages(message):
            self.checker.visit_call(node) 
Example 16
Project: python-netsurv   Author: sofia-netsurv   File: unittest_checker_python3.py    License: MIT License 5 votes vote down vote up
def test_bad_str_translate_call_infer_str(self):
        node = astroid.extract_node(
            """
         foobar = "hello world"
         foobar.translate(None, foobar) #@
         """
        )
        message = testutils.Message(
            "deprecated-str-translate-call", node=node, confidence=INFERENCE
        )
        with self.assertAddsMessages(message):
            self.checker.visit_call(node) 
Example 17
Project: python-netsurv   Author: sofia-netsurv   File: unittest_checker_python3.py    License: MIT License 5 votes vote down vote up
def test_ok_str_translate_call_integer(self):
        node = astroid.extract_node(
            """
         foobar.translate(None, 33) #@
         """
        )
        with self.assertNoMessages():
            self.checker.visit_call(node) 
Example 18
Project: python-netsurv   Author: sofia-netsurv   File: unittest_checker_python3.py    License: MIT License 5 votes vote down vote up
def test_ok_str_translate_call_not_str(self):
        node = astroid.extract_node(
            """
         foobar = {}
         foobar.translate(None, 'foobar') #@
         """
        )
        with self.assertNoMessages():
            self.checker.visit_call(node) 
Example 19
Project: python-netsurv   Author: sofia-netsurv   File: unittest_checker_python3.py    License: MIT License 5 votes vote down vote up
def test_six_ifexp_conditional(self):
        code = """
        from __future__ import absolute_import
        import six
        import string
        string.translate if six.PY2 else None
        """
        module = astroid.parse(code)
        with self.assertNoMessages():
            self.walk(module) 
Example 20
Project: meddle   Author: glmcdona   File: Cookie.py    License: MIT License 5 votes vote down vote up
def _quote(str, LegalChars=_LegalChars,
           idmap=_idmap, translate=string.translate):
    #
    # If the string does not need to be double-quoted,
    # then just return the string.  Otherwise, surround
    # the string in doublequotes and precede quote (with a \)
    # special characters.
    #
    if "" == translate(str, idmap, LegalChars):
        return str
    else:
        return '"' + _nulljoin( map(_Translator.get, str, str) ) + '"'
# end _quote 
Example 21
Project: meddle   Author: glmcdona   File: Cookie.py    License: MIT License 5 votes vote down vote up
def set(self, key, val, coded_val,
            LegalChars=_LegalChars,
            idmap=_idmap, translate=string.translate):
        # First we verify that the key isn't a reserved word
        # Second we make sure it only contains legal characters
        if key.lower() in self._reserved:
            raise CookieError("Attempt to set a reserved key: %s" % key)
        if "" != translate(key, idmap, LegalChars):
            raise CookieError("Illegal key value: %s" % key)

        # It's a good key, so save it.
        self.key                 = key
        self.value               = val
        self.coded_value         = coded_val
    # end set 
Example 22
Project: meddle   Author: glmcdona   File: fancy_getopt.py    License: MIT License 5 votes vote down vote up
def get_attr_name (self, long_option):
        """Translate long option name 'long_option' to the form it
        has as an attribute of some object: ie., translate hyphens
        to underscores."""
        return string.translate(long_option, longopt_xlate) 
Example 23
Project: meddle   Author: glmcdona   File: fancy_getopt.py    License: MIT License 5 votes vote down vote up
def translate_longopt(opt):
    """Convert a long option name to a valid Python identifier by
    changing "-" to "_".
    """
    return string.translate(opt, longopt_xlate) 
Example 24
Project: ironpython2   Author: IronLanguages   File: Cookie.py    License: Apache License 2.0 5 votes vote down vote up
def _quote(str, LegalChars=_LegalChars,
           idmap=_idmap, translate=string.translate):
    #
    # If the string does not need to be double-quoted,
    # then just return the string.  Otherwise, surround
    # the string in doublequotes and precede quote (with a \)
    # special characters.
    #
    if "" == translate(str, idmap, LegalChars):
        return str
    else:
        return '"' + _nulljoin( map(_Translator.get, str, str) ) + '"'
# end _quote 
Example 25
Project: ironpython2   Author: IronLanguages   File: Cookie.py    License: Apache License 2.0 5 votes vote down vote up
def set(self, key, val, coded_val,
            LegalChars=_LegalChars,
            idmap=_idmap, translate=string.translate):
        # First we verify that the key isn't a reserved word
        # Second we make sure it only contains legal characters
        if key.lower() in self._reserved:
            raise CookieError("Attempt to set a reserved key: %s" % key)
        if "" != translate(key, idmap, LegalChars):
            raise CookieError("Illegal key value: %s" % key)

        # It's a good key, so save it.
        self.key                 = key
        self.value               = val
        self.coded_value         = coded_val
    # end set 
Example 26
Project: ironpython2   Author: IronLanguages   File: fancy_getopt.py    License: Apache License 2.0 5 votes vote down vote up
def get_attr_name (self, long_option):
        """Translate long option name 'long_option' to the form it
        has as an attribute of some object: ie., translate hyphens
        to underscores."""
        return string.translate(long_option, longopt_xlate) 
Example 27
Project: ironpython2   Author: IronLanguages   File: fancy_getopt.py    License: Apache License 2.0 5 votes vote down vote up
def translate_longopt(opt):
    """Convert a long option name to a valid Python identifier by
    changing "-" to "_".
    """
    return string.translate(opt, longopt_xlate) 
Example 28
def _help():
    print "<----------------------------------------------------------------------------------------------->"
    print "[>] Untranslate Tools for Cryptography                                                          |"
    print "[>] Build by Summon Agus, blog: https://python.web.id                                           |"
    print "[>] Made for string was translate with `string.translate` from python modules.                  |"
    print "[+] --------------------------------------------------------------------------------------------|"
    print "[?] Untranslate left :   ./un_translate.py left [<number> or -f <for full>] <string_translate>  |"
    print "[?] Untranslate right:   ./un_translate.py right [<number> or -f <for full>] <string_translate> |"
    print "<----------------------------------------------------------------------------------------------->" 
Example 29
def _untranslate(command, length, en_translate):
    command         = sys.argv[1]
    length          = sys.argv[2]
    en_translate    = sys.argv[3]
    
    chrs = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
    #for complete chars, use this:
    #chrs = string.printable.replace(' \t\n\r\x0b\x0c', '')

    """This `_full_length()` function use if param of `length` is `-f`.
    So, there will returning `untranslate` with full length of param:`chrs`."""
    def _full_length():
        no = 0
        for numb in range(len(chrs)):
            no += 1
            make_trans = string.maketrans( shift(chrs, no, command), chrs)
            print string.translate(en_translate, make_trans )

    """This `_specific_length()` function use if param of `length` use specific number"""
    def _specific_length():
        no = 0
        for numb in range(int(length)):
            no += 1
            make_trans = string.maketrans( shift(chrs, no, command), chrs)
            print string.translate(en_translate, make_trans )

    """Define if `command` is `left or `right`, if not they, it will return to _help() function."""
    if command == 'left' or command == 'right':
        try:
            if length == '-f':
                _full_length()
            else:
                _specific_length()
        except ValueError:
            pass
    else:
        return _help() 
Example 30
Project: BinderFilter   Author: dxwu   File: Cookie.py    License: MIT License 5 votes vote down vote up
def _quote(str, LegalChars=_LegalChars,
           idmap=_idmap, translate=string.translate):
    #
    # If the string does not need to be double-quoted,
    # then just return the string.  Otherwise, surround
    # the string in doublequotes and precede quote (with a \)
    # special characters.
    #
    if "" == translate(str, idmap, LegalChars):
        return str
    else:
        return '"' + _nulljoin( map(_Translator.get, str, str) ) + '"'
# end _quote