【问题标题】:Python replace() function not working - although in a new functionPython replace() 函数不起作用 - 尽管在一个新函数中
【发布时间】:2020-10-15 21:10:58
【问题描述】:

我正在制作一个使用replace 函数将字符更改为x[alphabet number]/ 的函数。
现在它看起来像这样:

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/

这是为什么?

【问题讨论】:

  • 你没有给出原始输入——你能指出最终输出不同的确切位置吗?但总的来说,问题在于您的替换是一次完成一个而不是一次完成,因此在“反编译”阶段,例如,x24/25/ 将首先变为 x25/,然后简单地变为 y ,当我假设您可能只想要 x25/ 作为结果时?
  • 您好,首先,您能给我们提供意见吗?第二,你能解释一下在这个过程中什么地方会写回文件吗? (我推断是这种情况,因为你说'改回来')。第三,我认为用所有那些替换函数来做你正在做的事情并不是一个好主意。 IMO,您应该遍历字符串并根据您的规则构建一个新字符串...
  • 附带说明,这是一种痛苦的方式来实现这一点。有一些替代方法可以让您系统地处理所有字符。例如:re.sub('[a-z]', lambda x: f'x{ord(x.group(0)) - ord("a")+1}/', comp)
  • @AaronBentley,是的。我知道这样做是一种痛苦的方式。感谢您的回答!

标签: python str-replace


【解决方案1】:

你必须使用正则表达式模块

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))

不要将读取的文件放入您的compile 和decompile 函数中。

【讨论】:

    【解决方案2】:
    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)
    

    这段代码完美运行,做同样的事情,而不是一个字符串添加文件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-06
      • 2021-12-23
      • 1970-01-01
      • 2021-10-24
      相关资源
      最近更新 更多