Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,919 questions

51,852 answers

573 users

How to replace a random word in a string with a random word from a list of words using Python

2 Answers

0 votes
import random
 
def random_word_replacement(s, replacement_words):
   stringwords = s.split()
 
   random_index_in_string = random.randint(0, len(stringwords) - 1)
   random_index_in_replacementwords = random.randint(0, len(replacement_words) - 1)
	
   stringwords[random_index_in_string] = replacement_words[random_index_in_replacementwords]
	
   result = ' '.join(stringwords)
   
   return(result)


s = "The quick brown fox jumps over the lazy dog" 
replacement_words = ["c#", "c++", "go", "rust", "python"]

result = random_word_replacement(s, replacement_words)

print(result)


'''
run:
 
The c# brown fox jumps over the lazy dog
   
'''

 



answered 5 hours ago by avibootz
0 votes
import random

def replace_random_word(s, replacement_words):
    stringwords = s.split()
    if not stringwords or not replacement_words:
        return s  # nothing to do

    idx = random.randrange(len(stringwords))          # pick random word index
    random_word = random.choice(replacement_words)    # pick random replacement
    stringwords[idx] = random_word                    # replace it

    return " ".join(stringwords)

text = "The quick brown fox jumps over the lazy dog"
replacement_words = ["c#", "c++", "java", "rust", "python"]

result = replace_random_word(text, replacement_words)
print(result)



'''
run:
 
The quick brown c++ jumps over the lazy dog
   
'''

 



answered 5 hours ago by avibootz

Related questions

2 answers 152 views
...