Skip to main content
 首页 » 编程设计

python之在 Python 中,如何用列表中的随机项替换字符串中的单词

2025年05月04日22kevingrace

我正在尝试采用某种字符格式 _n_ 并将其替换为数组中的随机字符串。

在 wordlibrary.py 中:

    import random 
 
    nouns =   ['wombat','zebra','elephant','lamp','desk','computer','python','castle','king','scribble','doodle','motorcycle','car','train','plane'] 
 
    def chooseNoun(): 
        randomNoun = random.randint(0,len(nouns)) 
        nounChoice = nouns[randomNoun-1] 
        return nounChoice 

现在,在 storyCreator.py 中:

    import wordLibrary 
 
    originalString = input("Type a sentence or story. Use \'_n_\' to denote a noun, \'_adj_\' to denote an adjective, \'_v_\' to denote a verb, \'_adv_\' to denote an adverb, or \'_l_\' to denote a location.     Type Here: ") 
 
    nounCheck = '_n_' 

如何在字符串中找到 _n_ 并每次用列表中的随机单词替换它?

请您参考如下方法:

同时使用str.replace和random.choice,并记得分配新的字符串:

while '_n_' in oldString: 
    oldString = oldString.replace('_n_', random.choice(nouns))