Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Need help with .replace()
#1
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?
Reply
#2
You could use a dictionary and keys method to replace each letter with its respective number.
pyzyx3qwerty
"The greatest glory in living lies not in never falling, but in rising every time we fall." - Nelson Mandela
Need help on the forum? Visit help @ python forum
For learning more and more about python, visit Python docs
Reply
#3
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Search & Replace - Newlines Added After Replace dj99 3 3,404 Jul-22-2018, 01:42 PM
Last Post: buran

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020