TransWikia.com

Python replace() function not working - although in a new function

Stack Overflow Asked on February 7, 2021

I’m making a function that changes characters to x[alphabet number]/ using the replace function.
Right now it looks like this:

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) 

This will be the output:

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/'

So that is what I wanted, but then if I want to change it back, it won’t work.

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)

But now, this will be the output.

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/

Why is this?

2 Answers

You have to use the Regex module

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

Do not put the file reading in your compile and decompile functions.

Answered by rioV8 on February 7, 2021

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)

This code works perfect, do the same thing just instead of a string add the file.

Answered by CForce99 on February 7, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP