将 Javascript 函数转换为 Python

我是 Python 新手,我很难将这个 Javascript 箭头函数翻译成 Python。当我找到'\x1D'时,我无法制作我在JS中使用子字符串的部分来获取循环中的下3个值。任何提示或建议?


module.exports = edi => {

  let decompressedEdi = ''

  let lastCompressor = 0

  for (let i = 0; i <= edi.length; i++) {

    if (edi[i] === '\x1D') {

      let decimal = parseInt(edi.substring(i + 1, i + 3), 16)

      let repeater = edi[i + 3]

      decompressedEdi +=

        edi.substring(lastCompressor, i) + repeater.repeat(decimal)

      lastCompressor = i + 4

    }

  }

  decompressedEdi += edi.substring(lastCompressor, edi.length)

  return decompressedEdi.replace(/(\r\n|\n|\r)/gm, '')

}


当年话下
浏览 286回答 2
2回答

一只名叫tom的猫

在python中,字符串可以像数组一样切片:for i, c in enumerate(edi):&nbsp; if c == '\x1D':&nbsp; &nbsp; decimal = int(edi[i+1:i+3], 16)int 函数具有以下签名: int(str, base)

慕姐8265434

from re import subdef decompress(edi):&nbsp; &nbsp; decompressed = ""&nbsp; &nbsp; last_compressor = 0&nbsp; &nbsp; for i, c in enumerate(edi):&nbsp; &nbsp; &nbsp; &nbsp; if c == "\x1D":&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; repetitions = int(edi[i + 1: i + 3], 16)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; repeating_char = edi[i + 3]&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; decompressed += edi[last_compressor:i] + repeating_char * repetitions&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; last_compressor = i + 4&nbsp; &nbsp; decompressed += edi[last_compressor:-1]&nbsp; &nbsp; return sub("\r\n|\n|\r", decompressed)我如何阅读代码随意忽略这一点,但它可能会有所帮助。给定edi其中有一个len,对于每个edi匹配的\x1D,获取edi从index + 1到index + 3作为 设置为 的十六进制整数的子串decimal。The repeateris the index + 3'th element of edifor each element and it is expected to be a str. 它将重复 中定义的十六进制次数decimal,但仅在edifromlastCompressor到当前索引的子字符串之后重复。在\x1D匹配的每次迭代中,lastCompressor增加 4。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript