首页 > 解决方案 > Python字符串随机替换

问题描述

我对 python 感兴趣,它的简单性、可读性和灵活性。我想随机替换字符串。我的意思是

animals = ["cat", "dog", "monkey", "tiger"]

template = "$animal fights with $animal. $animal can play with $animal. Sth $animal sth $animal ..."

我想在每次出现$animal时用随机选择的元素替换。animals例如,我想这样输出"dog fights with cat. cat can play with tiger. Sth monkey sth dog ..."。当然,可以用无聊的代码来解决。但是有没有“ Pythonic ”的单行代码?

标签: pythonpython-2.7

解决方案


对于简单的情况,我更喜欢这样的东西:

import random

animals = ["cat", "dog", "monkey", "tiger"]


def ra():
    return random.choice(animals)


print(f'{ra()} fights with {ra()}. {ra()} can play with {ra()}. Sth {ra()} sth {ra()} ...')

但这更接近您的起点,您可能更喜欢它:

import re
import random

animals = ["cat", "dog", "monkey", "tiger"]
template = "$animal fights with $animal. $animal can play with $animal. Sth $animal sth $animal ..."

print(re.sub(r'\$animal', lambda _: random.choice(animals), template))

请注意,这两种解决方案都不关心您要替换多少动物。


推荐阅读