Home > Enterprise >  Convert js fromCharCode to python native code
Convert js fromCharCode to python native code

Time:10-07

How can i convert this function to python native code

function replac_ch(a) {
    return a.replace(/[A-Za-z]/g, function (a) {
        return String.fromCharCode(a.charCodeAt(0)   ('M' >= a.toUpperCase() ? 13 : - 13))
    })
}

CodePudding user response:

Have you tried anything in python yet?

re is the regex library.

to make something uppercase use string.upper()

The ternary operator is: 13 if 'M' >= a.upper() else -13

anonymous functions use lambda

You can use char() and ord() to move from char code to character and vice versa.

CodePudding user response:

this is how i solve it the same result from js and python

import re

text = "1.w-952168.1.2.PzaDdMBdaBowPJvNa68GYQ,,.vgNsGnZefWSfDD1ygFFWXKcTstrPc68-aL1DNHU9XsiSEGo8fWBAGTuIWNliaXx-cqaeOIBvq8YrgzYjbGk6BrB8MhrCSy1YJKFhV8il-MG94tXPPbpHiSePsqYOBcARhnHVh968P2152H8Pc8o1Eu10lMUR5_jB-1UX5-wQSzUToSndof66nlwcaAi7KqdgRUvXbT6iLuHOXO2GsuJ1bE3Gv3KIT0qE2eWCNBGgwtuD1yoWVA2sXqnULl62aauc"
    
    
    def replac_ch(text):
        val = []
        for i in text:
            val.append(re.sub(r"[A-Za-z]", chr(ord(i[0]) (13 if 'M' >= i.upper() else -13)), i))
        return ''.join(val)
        
    print(replac_ch(text))
  • Related