I am making a program that generates the phrase, "The enemy of my friend is my enemy!" actually, I want this phrase to print out a random permutation of (Friend/Enemy) in each place every time it is re-ran.
so far I got the code to print out the same word 3 times in each, but not a different word in each place.
I couldn't get python to access each string individually from a list. Any ideas?
Thanks!
`
import random
en = 'Enemy'
fr = 'Friend'
words = en, fr
for word in words:
sentence = f"The {word} of my {word} is my {word}!"
print(sentence)
`
CodePudding user response:
If you want to print random sentence each time a script is run, you can use random.choices
to choose 3 words randomly and str.format
to format the new string. For example:
import random
en = "Enemy"
fr = "Friend"
words = en, fr
sentence = "The {} of my {} is my {}!".format(*random.choices(words, k=3))
print(sentence)
Prints (randomly):
The Enemy of my Friend is my Friend!
CodePudding user response:
I'd make more changes to the code as it looks like the code in the question is trying to use the wrong tools.
import random
words = ['Enemy', 'Friend']
# three independent draws from your words
w1 = random.choice(words)
w2 = random.choice(words)
w3 = random.choice(words)
# assemble together using an f-string
sentence = f"The {w1} of my {w2} is my {w3}!"
print(sentence)
Not sure if this will be easier to understand, but hopefully!