Python Forum

Full Version: Need help with .replace()
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Greetings,im really new to python and im trying to create a simple encryption program (basically ill input a text and it'll get converted to numbers, nothing complicated for now). Heres my code so far:
a = 1
b = 2
c = 3
d = 4
e = 5
f = 6
g = 7
h = 8
#just random letters and their respective numbers

fr = open('tryy.txt', 'r')
fw = open('tryy.txt', 'a')

for elem in fr:
    fw.write(elem.replace('a', str(a))) & fw.write(elem.replace('b', str(b)))

fr.close()
fw.close()
the problem is that when i try using this, (my basic example text is just "ab"), instead of converting both characters to "12" as it should, the program returns a text file like this:
ab

1b

a2
any advice on how to correct the code here?
You could use a dictionary and keys method to replace each letter with its respective number.
One problem is that replace does not replace, it creates a new string. I want to replace letters with numbers in a string:
letters = 'abcdefgh'
string = 'The quick brown fox jumps over the lazy dog'

for index, letter in enumerate(letters):
    string.replace(letter, str(index+1))

print(string)
Output:
The quick brown fox jumps over the lazy dog
Python strings are immutable, they cannot be changed. The replace function creates a new string when the replaced letters while the original string remains unchanged. To make the above code work I need to use the string returned by replace.
letters = 'abcdefgh'
string = 'The quick brown fox jumps over the lazy dog'

for index, letter in enumerate(letters):
    string = string.replace(letter, str(index+1))

print(string)
Output:
T85 qui3k 2rown 6ox jumps ov5r t85 l1zy 4o7
Knowing that replace does not modify the string, it should be easy for you to see why your code does not work. In the original you replace 'a' with '1' and print the modified string. Then you replace 'b' in the original string with '2' and print the modified string.