0

好的,所以这可能有点神秘。

我有一份食物清单,我从中随机选择物品。我在另一个列表中使用它来谈论选定的食物,但是这些字符串可以在句子的开头和结尾都包含食物名称。

例子:

default breakfast_food_list = ['pancakes','bacon and eggs','scones','sandwiches','beans and bacon','quiche','cereal','muffins']

default breakfast_nice_list = [
            ['I love your {0}',2,'fm_rel'],
            ['Ah, I just love those {0}',2,'fm_rel'],
            ['{0} is fine',1,'fm_rel'],
]

$ breakfast_select = random.randint(0,len(breakfast_food_list)-1)
$ breakfast_nice = breakfast_nice_list[breakfast_nice_select][0]

我像这样显示这些:

$ breakfast_reply = breakfast_nice.format(breakfast_food)

现在,我可以将 .captialize() 打在最后,但这会使其大写,即使它位于句子的末尾或中间。

所以,我正在寻找一种解决方案,当它是句子中的第一个单词并且只有第一个单词时,它会被大写......

4

2 回答 2

1

编辑:我已经更新了问题评论中输入的答案(以及这个答案)。//编辑

你可以尝试这样的事情:

from random import choice

default breakfast_food_list = ['pancakes','bacon and 
     eggs','scones','sandwiches','beans and bacon','quiche','cereal','muffins']

default breakfast_nice_list = [
    ['I love your {0}',2,'fm_rel'],
    ['Ah, I just love those {0}',2,'fm_rel'],
    ['{0} is fine',1,'fm_rel']]

words = choice(breakfast_nice_list)[0]
food = choice(breakfast_food_list)
output = words.format(food).capitalize()
于 2018-02-14T03:17:57.533 回答
-2

如果您使用的是 Python3.6,则可以进行一些重新排列并使用f-strings。喜欢

breakfast_choice = breakfast_food_list[breakfast_select]

breakfast_reply = f"{breakfast_choice.capitalize()} is fine"

于 2018-02-14T03:19:00.007 回答