【问题标题】:Replacing text in tags替换标签中的文本
【发布时间】:2018-03-02 11:56:22
【问题描述】:

我在尝试用 Python 替换字符串中的标签时遇到了问题。

我现在有的是文字:

you should buy a {{cat_breed + dog_breed}} or a {{cat_breed + dog_breed}}

其中cat_breeddog_breed 是猫和狗品种的列表。

我想结束的是:

you should buy a Scottish short hair or a golden retriever

我希望将标签替换为两个列表之一中的随机条目。

我一直在查看re.sub(),但我不知道如何解决这个问题,而不仅仅是在两个标签中得到相同的结果。

【问题讨论】:

    标签: python regex string replace


    【解决方案1】:

    使用random.sample 从总体中获取两个唯一元素。

    import random
    cats = 'lazy cat', 'cuddly cat', 'angry cat'
    dogs = 'dirty dog', 'happy dog', 'shaggy dog'
    
    print("you should buy a {} or a {}".format(*random.sample(dogs + cats, 2)))
    

    这里没有理由使用正则表达式。只需使用 string.format 代替。

    【讨论】:

      【解决方案2】:

      我希望下面的想法能给你一些关于如何完成任务的想法:

      list1 = ['cat_breed1', 'cat_breed2']
      list2 = ['dog_breed1', 'dog_breed2']
      
      
      a = random.choice(list1)
      b = random.choice(list2)
      
      
      sentence =  "you should buy a %s or a %s" %(a, b)
      

      【讨论】:

      • 为什么你认为它没有提供答案?我让他走上了正确的道路:向他展示了如何从列表中随机选择一个项目以及如何使用 %s 将其放入字符串中。
      • 确实,看来我犯了一个错误。对此感到抱歉。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-05
      • 2019-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多