So I am confuse of what should i do this is using Python I have a txt string tha
ID: 3596649 • Letter: S
Question
So I am confuse of what should i do this is using Python
I have a txt string that I am imported it is writen like this:
-------------------------
Kick to the gut, punch to the head, kick to the leg,
punch to the heart, kick to the ribs. and you win
--------------------------
So I am confuse of what should i do to replace kick to punch and punch to kick
this is what i have done so far
i = open("kick.txt", 'r')
for word in i:
for word2 in i:
if word2 == "kick":
new=+ world2.replace("kick","punch")
print new
so this si just what i think it can be but i print nothing what should i do to do it
please help me to understand more about double loop and .replace
Explanation / Answer
In this python code, you do not require to double loops.
Double loops are required when you want to iterater over a sentEnce more than once. Here
we iterate of the loop only once and check if it is Kick or punch
we take the function replace(a,b) WHICH REPLACEs the string a by string b,
then we add the changed string to a new string s and print it.
I hope its clear, If not you can comment below.
Kindly see the output below.
*************************************************************************************************
i = open("kick.txt", 'r')
new=""
s=""
for word in i.split():
if word == "kick" :
new= word.replace("kick","punch")
elif word == "Kick":
new = word.replace("Kick","Punch")
elif word == "punch":
new= word.replace("punch","kick")
else:
new = word
s = s + " " + new
print s
*************************************************************************************************
Sample output:
Punch to the gut, kick to the head, punch to the leg, kick to the heart, punch to the ribs. and you win
**************************************************************************************************
I hope this helps you.
If you find my answer useful, kindly rate it.
All the best. :)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.