Python 3:使用多个相同的关键字格式化字符串,但使用唯一的字符串来替换它们

时间:2015-10-18 19:23:31

标签: python string python-3.x replace keyword

我想知道如何在Python 3.4中使用列表格式化多个相同的关键字。我设置它的方式是用户可以传入一个字符串,该字符串具有多个关键字,用于程序将在其位置生成的名称,结果应该是一个句子,其中的关键字被替换为名称。

我已经创建了一个方法来根据程序在用户传入的字符串中看到的数量生成名称,但由于字符串的性质,不能立即替换它们。由于字符串具有多个相同的关键字(例如{name}),因此我需要能够用唯一的字符串替换它们中的每一个。这在Python 3.4中是否可行?

用户传入的字符串可以是

"{name} had a wonderful day at the park, but then {name} came and ruined it"

并且在程序生成名称之后它应该是

"John had a wonderful day at the park, but then Bob came and ruined it"

干杯。

编辑:要添加,我没有找到任何关于使用列表或拥有多个关键字但有独特替代品的信息,所以如果我必须采取其他方式而不是替换它也可以。

5 个答案:

答案 0 :(得分:3)

您可以将string.replace与可选的count参数一起使用,并将其限制为每次只替换一个名称:

>>> names = ['John', 'Bob']
>>> message = "{name} had a wonderful day at the park, but then {name} came and ruined it"
>>> i = 0;
>>> while '{name}' in message:
...     message = message.replace('{name}', names[i], 1)
...     i += 1
... 
>>> message
'John had a wonderful day at the park, but then Bob came and ruined it'

答案 1 :(得分:2)

您可以使用count参数:

>>> s = "{name} had a wonderful day at the park, but then {name} came and ruined it"
>>> s = s.replace('{name}', 'John', count=1)
>>> s
'John had a wonderful day at the park, but then {name} came and ruined it'

>>> s = s.replace('{name}', 'Bob', count=1)
>>> s
'John had a wonderful day at the park, but then Bob came and ruined it'

答案 2 :(得分:2)

如果您根据每次替换的次数预先生成了一个项目列表,则可以使用re.sub以编程方式从列表中选择下一个项目。这将比import re # Function to look up an item and return the next thing in its list. def replace(m): return D[m.group(1)].pop(0) D = {'name' : ['John','Bob'], 'place' : ['park']} text = "{name} had a wonderful day at the {place}, but then {name} came and ruined it" new_text = re.sub('{(.*?)}',replace,text) print(new_text) 具有更好的性能,尤其是如果你有一个大词典关键词和一个大文本。

例如:

John had a wonderful day at the park, but then Bob came and ruined it

输出:

format

但是,您似乎想为不同的名称使用不同的变量。然后你可以将D = {'name1':'John', 'name2':'Bob', 'place':'park'} text = "{name1} had a wonderful day at the {place}, but then {name2} came and ruined it. {name2} is a jerk!" print(text.format(**D)) 与字典一起使用:

导入重新

John had a wonderful day at the park, but then Bob came and ruined it. Bob is a jerk!

输出:

import java.util.*;

public class Coins{

    public static int findMinCoins(int[] currency, int amount) {
        int i, j, min, tempSolution;

        min = amount;

        for (i = 0; i < currency.length; i++) {
            if (currency[i] == amount) {
                return 1;
            }
        }

        for (j = 1; j <= (amount / 2); j++) {
            tempSolution = findMinCoins(currency, j) + findMinCoins(currency, amount - j);
            if (tempSolution < min) {
                min = tempSolution;
            }
        }
        return min;
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int[] USA =
        {1, 5, 10, 25, 50};
        System.out.println("Please enter an integer amount.");
        int amount = in.nextInt();
        int minCoins = findMinCoins(USA, amount);
        System.out.println("The minimum number of coins to make " + amount + " in United States currency is " + minCoins + ".");
        System.out.println("The coins used were:");
        /*Print coins used to find minCoins.*/
        in.close();
    }
}

答案 3 :(得分:0)

如果我理解你的话,这应该有效:
first_name = Bob
second_name = Sam
"%s had a wonderful day at the park, but then %s came and ruined it" % (first_name, second_name)

可能是最干净的方法

答案 4 :(得分:0)

如果短语总是在示例中间隔良好,则可以执行

s = "{name} had a wonderful day at the park, but then {name} came and ruined it"
names = ['John', 'Bob']
ni = iter(names)
outs = ' '.join(next(ni) if el=='{name}' else el for el in s.split())
print(outs)

产生

'John had a wonderful day at the park, but then Bob came and ruined it'