Discord Server Red Security Twitter Donation to Red Security Red Security Youtube Channel Red Security Tumblr Profile
Login or Register to Hide ads and Accessing all features on the forum

Tutorial 

Dictionary Use in real life example

0 Replies, 963 Views

[Image: BFMMlbcQvml9HSqXcvNp]
Change a word in text File using Dictionary:
                     Hi guys, I hope you are doing well. In today’s thread I am going to show you how you can use a python dictionary data structure to change a word in a text file so without wasting any time let’s get started. First of all we have to load our text file in our program
 
Code:
file = open('SomeText.txt')


After that now we will store it into a string named ‘text’

Code:
text = file.read()

Now we will create a dictionary that stores the existing word as key and the word that we want to add as value just like this..

Code:
d = {}

d['left'] = '__left__'
d['right'] = '__Right__'
d['printPicnic()'] = '__This is A function()__'


So now we want to change left with ‘__left__’  and so on. You can change the values by your wish and now we will replace these words in our string ‘text’..

Code:
for key in d:
    text = text.replace(key, d[key])

And now if we want to print the text we will get the new string..

Code:
print(text)

So the whole code will be like this 


Code:
file = open('SomeText.txt')
text = file.read()

d = {}

d['left'] = '__left__'
d['right'] = '__Right__'
d['printPicnic()'] = '__This is A function()__'

for key in d:
    text = text.replace(key, d[key])

print(text)

The result of this code will look like this...

   

So that's it for now. If you have any questions related to python you can ask in the comment section or directly DM me. Thank you!

"Keep Good care of your Health
Allah Hafiz and Good Bye Till the next post"
Love me like you do Heart
(This post was last modified: 06-16-2022, 06:34 PM by Covid-19.)



Users browsing this thread: 1 Guest(s)