Python replace()函数不起作用-尽管在新函数中

Python replace()函数不起作用-尽管在新函数中,python,str-replace,Python,Str Replace,我正在使用replace函数将字符更改为x[字母数字]/。 现在看起来是这样的: def compile(File): f=open(File,'r') #open the file parameter content=f.read() #create the content variable. a=content.replace('a','x1/').replace('b','x2/').replace('c','x3/').replace('d','x4/').rep

我正在使用
replace
函数将字符更改为
x[字母数字]/

现在看起来是这样的:

def compile(File):
    f=open(File,'r') #open the file parameter
    content=f.read() #create the content variable.
    a=content.replace('a','x1/').replace('b','x2/').replace('c','x3/').replace('d','x4/').replace('e','x5/').replace('f','x6/').replace('g','x7/')... # and so on.
    print(a) 
这将是输出:

x24/13/x24/1/x24/11/x24/5/x32/x27/x24/6/x24/21/x24/14/x24/3/x24/20/x24/9/x24/15/x24/14/x28/x32/x24/19/x24/1/x25/x32/'Hx24/9/x30/'x29/x24/1/x24/19/x24/11/x32/'Ux24/19/x24/5/x24/18/x24/14/x24/1/x24/13/x24/5/x28/x32/'x29/x24/1/x24/19/x24/11/x32/'Px24/1/x24/19/x24/19/x24/23/x24/15/x24/18/x24/4/x28/x32/'
所以这就是我想要的,但是如果我想把它改回去,它就行不通了

def decompile():
    comp=open(run,'r').read()
    a=comp.replace('x1/','a').replace('x2/','b').replace('x3/','c').replace('x4/','d').replace('x5/','e').replace('x6/','f').replace('x7/','g')... #and so on.
    print(a)
但现在,这将是输出

x13/x1/x11/x5/ $x6/x21/x14/x3/x20/x9/x15/x14/: x19/x1/y 'Hx9/!' | x1/x19/x11/ 'Ux19/x5/x18/x14/x1/x13/x5/: ' | x1/x19/x11/ 'Px1/x19/x19/x23/x15/x18/x4/: '
$x6/x21/x14/x3/x20/x9/x15/x14/
为什么会这样

def compile(a):
    content= a
    a=content.replace('a','x1/').replace('b','x2/').replace('c','x3/').replace('d','x4/').replace('e','x5/').replace('f','x6/').replace('g','x7/')# and so on.
    print(a) 

def decompile(b):
    comp= b
    s=comp.replace('x1/','a').replace('x2/','b').replace('x3/','c').replace('x4/','d').replace('x5/','e').replace('x6/','f').replace('x7/','g')
    print(b) 

g = "abcdefg"
compile(g)
decompile(g)

这段代码非常好用,只需做同样的事情,而不是用字符串来添加文件。

您必须使用Regex模块

import re

def compile(content):
  return re.sub(r'[a-z]', lambda match: f"x{ord(match.group())-ord('a')+1}/", content)

def decompile(content):
  return re.sub(r'x(\d+)/', lambda match: chr(int(match.group(1))-1+ord('a')), content)

g = "a13bc35defg"
r = compile(g)
print(r)
print(decompile(r))

不要将文件读取放在
编译
反编译
函数中。

您没有提供原始输入-您能准确指出最终输出不同的确切位置吗?但总的来说,问题是每次替换一个而不是一次完成所有替换,因此在“反编译”阶段,例如,
x24/25/
将成为第一个
x25/
,然后是简单的
y
,当我假设您可能只希望结果是
x25/
?嘿,首先,你能给我们一些建议吗?第二,你能解释一下在这个过程中,它将在哪里被写回一个文件吗?(我推断是这样的,因为你说‘把它换回来’)。第三,我认为这不是一个好主意,你正在做的所有这些取代func。在我看来,您应该迭代字符串,并根据您的规则构建一个新字符串……作为旁注,这是一个痛苦的方法来完成这一点。有一些替代方案可以让您系统地处理所有字符。例如:re.sub('[a-z]',lambda x:f'x{ord(x.group(0))-ord(“a”)+1}/',comp)@AaronBentley,是的。我知道这样做很痛苦。谢谢你的回答!