python - 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 ”的单行代码?
解决方案
对于简单的情况,我更喜欢这样的东西:
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))
请注意,这两种解决方案都不关心您要替换多少动物。
推荐阅读
- java - 找不到字段映射器,考虑定义一个 bean
- python - 如何从另一个列表中创建特定序列的新列表?
- vb.net - 如何配置 EAGetMail DLL 选项以使日期搜索工作?
- json - Json 已解析,但无法在 UI 中显示数据颤动 [已解决]
- ios - NativeScript > iOS - 应用程序崩溃 - XC_BAD_ACCESS (SIGSEGV) 分段错误:11
- r - 闪亮的 if else 语句
- google-workspace - 将服务帐户分配给工作区 (GSuite) 中的组管理员角色
- python - 如何多线程一个程序并将结果返回给 main.py?
- c# - 尝试激活“控制器”时无法解析“Microsoft.Extensions.Logging.ILogger”类型的服务
- python - 如何将 docx 内容放在数据框列中?