+
81
-

js如何写一段代码格式化python代码字符串?

js如何写一段代码格式化python代码字符串?

网友回复

+
1
-
   <script type="text/javascript">
      function formatPython(code) {
  let formatted = code;
  
  // 在函数、类、方法定义前插入空行
  formatted = formatted.replace(/^(\s*)(def|class)/gm, '$1\n$1$2');
  
  // 在多行注释前插入空行
  formatted = formatted.replace(/^(\s*)#/gm, '$1\n$1#');

  // 在操作符前后插入空格
  formatted = formatted.replace(/\s*([=<>&|\+\-\*/%])\s*/g, ' $1 ');
  
  // 统一使用4个空格缩进
  formatted = formatted.replace(/^\t+/gm, match => ' '.repeat(4 * match.length));

  return formatted;
}

// 使用方式
const code = `def func():
\tprint('hello')
`;

const formattedCode = formatPython(code);
console.log(formattedCode)
	
    </script>

我知道答案,我要回答