Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/311.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 以字符串格式设置参数的模板_Python_String_Python 3.x_Formatting - Fatal编程技术网

Python 以字符串格式设置参数的模板

Python 以字符串格式设置参数的模板,python,string,python-3.x,formatting,Python,String,Python 3.x,Formatting,我正在为字符串格式中的模板寻找一个包或任何其他方法(手动替换除外) 我想实现这样的目标(这只是一个示例,您可以了解想法,而不是实际的工作代码): 因此输出将为: 我热爱科学 我怎样才能做到这一点?我一直在找,但找不到合适的。可能使用了错误的命名术语 如果没有现成的软件包,我很乐意阅读一些关于自己编写代码的技巧。为什么不使用字典呢 options = {'what': ('like', 'love'), 'item': ('pizza', 'space', 'science')} print("

我正在为字符串格式中的模板寻找一个包或任何其他方法(手动替换除外)

我想实现这样的目标(这只是一个示例,您可以了解想法,而不是实际的工作代码):

因此输出将为

我热爱科学

我怎样才能做到这一点?我一直在找,但找不到合适的。可能使用了错误的命名术语



如果没有现成的软件包,我很乐意阅读一些关于自己编写代码的技巧。

为什么不使用字典呢

options = {'what': ('like', 'love'), 'item': ('pizza', 'space', 'science')}
print("I " + options['what'][1] + ' ' + options['item'][2])
这句话的回报是:“我爱科学”

或者,如果您想要一种方法,使您不必重新格式化以容纳/删除空格,则将其合并到字典结构中,如下所示:

options = {'what': (' like', ' love'), 'item': (' pizza', ' space', ' science'), 'fullstop': '.'}
print("I" + options['what'][0] + options['item'][0] + options['fullstop'])

这会返回:“我喜欢比萨饼。”

我可能会使用列表或元组来表示
内容和
项目,因为这两种数据类型都保留插入顺序

what = ['like', 'love']
item = ['pizza', 'space', 'science']

text = "I {what} {item}".format(what=what[1],item=item[2])
print(text)    # I like science
甚至这也是可能的

text = "I {what[1]} {item[2]}".format(what=what, item=item)
print(text)  # I like science

希望这有帮助

我认为使用列表就足够了,因为

输出:
我热爱科学

因为没有人能提供一个恰当的答案来直接回答我的问题,所以我决定自己研究这个问题

我不得不使用双括号,因为单括号是为字符串格式保留的

我最后上了以下课程:

class ArgTempl:
    def __init__(self, _str):
        self._str = _str

    def format(self, **args):
        for k in re.finditer(r"{{(\w+):([\w,]+?)}}", self._str,
                             flags=re.DOTALL | re.MULTILINE | re.IGNORECASE):
            key, replacements = k.groups()

            if not key in args:
                continue

            self._str = self._str.replace(k.group(0), replacements.split(',')[args[key]])

        return self._str
这是一个原始的、5分钟编写的代码,因此缺少检查等等。它工作正常,可以很容易地进行改进

在Python2.7和3.6上测试~

用法:

test = "I {{what:like,love}} {{item:pizza,space,science}}"
print(ArgTempl(test).format(what=1, item=2))
> I love science

感谢您的回复。

您使用的是python>3.6还是python<3.6?我使用的是可用的最新版本,因此>3.6。您应该将
what[2]
item[3]
更改为
what[1]
item[2]
,否则您将得到一个
索引器

class ArgTempl:
    def __init__(self, _str):
        self._str = _str

    def format(self, **args):
        for k in re.finditer(r"{{(\w+):([\w,]+?)}}", self._str,
                             flags=re.DOTALL | re.MULTILINE | re.IGNORECASE):
            key, replacements = k.groups()

            if not key in args:
                continue

            self._str = self._str.replace(k.group(0), replacements.split(',')[args[key]])

        return self._str
test = "I {{what:like,love}} {{item:pizza,space,science}}"
print(ArgTempl(test).format(what=1, item=2))
> I love science