在Python中反转C样式格式字符串(`%`) [英] Reversing C-style format strings in Python (`%`)

查看:98
本文介绍了在Python中反转C样式格式字符串(`%`)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个格式为'template'*的字符串,

Suppose I have a 'template'* string of the form,

>>> template = """My %(pet)s ate my %(object)s.
... This is a float: %(number)0.2f.
... %(integer)10d is an integer on a newline."""

使用此模板,我可以生成一个新字符串,

With this template I can generate a new string with,

>>> d = dict(pet='dog', object='homework', number=7.7375487, integer=743898,)

>>> out_string = template % d

>>> print(out_string)
My dog ate my homework.
This is a float: 7.74.
    743898 is an integer on a newline.

太好了!

我想将模板应用于 out_string ,以生成新的 dict

I'd like to apply template to out_string to produce a new dict. Something like,

>>> d_approx_copy = reverse_cstyle_template(out_string, template)
>>> print(d_approx_copy)
{pet='dog', object='homework', number=7.74, integer=743898,}

是否有Python方式来做到这一点? **

Is there a Pythonic way to do this? Does an implementation already exist?**

*:我没有使用模板,因为AFAIK目前不支持反转

*: I'm not using Template because, AFAIK, they don't currently support reversing.

**:我知道风险数字(从 7.7375487 7.74 )。我可以解决。我只是在寻找一种简单的方法来完成此操作。

**: I am aware of the risks associated with the loss of precision in number (from 7.7375487 to 7.74). I can deal with that. I'm just looking for a simple way to do this.

推荐答案

在开发此问题时,我找不到现有的工具可以通过这种方式来反转C样式的字符串。也就是说,我认为该问题的答案是:我正在寻找的 reverse_cstyle_template 函数当前不存在。

As I was developing this question, I could not find an existing tool to reverse C-style strings this way. That is, I think the answer to this question is: the reverse_cstyle_template function I was looking for does not currently exist.

在研究此主题的过程中,我发现许多与此问题相似的问题/答案,它们使用正则表达式(例如 1 2 3 )。但是,我想要更简单的方法,并且不想使用其他模板字符串来进行格式设置和解析。

In the process of researching this topic, I found many questions/answers similar to this one that use regular expressions (e.g. 1, 2, 3). However, I wanted something simpler and I did not want to have to use a different template string for formatting vs. parsing.

这最终导致我格式字符串语法 Richard Jones parse 包。例如,上面的模板是以格式字符串语法编写的,

This eventually led me to format string syntax, and Richard Jones' parse package. For example the template above is written in format string syntax as,

>>> template = """My {pet} ate my {object}.
... This is a float: {number:0.2f}.
... {integer:10d} is an integer on a newline."""

使用此模板,可以使用内置的 str.format 创建一个基于 d 的新字符串,

With this template, one can use the built-in str.format to create a new string based on d,

template.format(**d)

然后使用解析包以获取 d_approx_copy

>>> from parse import parse
>>> d_approx_copy = parse(template, out_string).named

请注意这里我已经访问了 .named 属性。这是因为 parse 返回一个 Result 对象(在解析中定义),该对象捕获了两个命名 fixed 格式说明符。例如,如果使用,

Note here that I've accessed the .named attribute. This is because parse returns a Result object (defined in parse) that captures both named and fixed format specifiers. For example if one uses,

>>> template = """My {pet} {}ate my {object}.
... This is a float: {number:0.2f}.
... {integer:10d} is an integer on a newline.
... Here is another 'fixed' input: {}"""

>>> out_string = template.format('spot ', 7, **d)

>>> print(out_string)
My dog spot ate my homework.
This is a float: 7.74.
    743898 is an integer on a newline.
Here is another 'fixed' input: 7

然后我们可以获取固定名称

Then we can get the fixed and named data back by,

>>> data = parse.parse(template, out_string)

>>> print(data.named)
{'pet': 'dog', 'integer': 743898, 'object': 'homework', 'number': 7.74}

>>> print(data.fixed)
('spot ', '7')

酷,

希望有一天,此功能将作为内置功能包含在 str 或< a href = https://docs.python.org/2/library/string.html#template-strings rel = nofollow noreferrer>模板。目前,尽管解析可以很好地满足我的目的。

Hopefully someday this functionality will be included as a built-in either in str, or in Template. For now though parse works well for my purposes.

最后,我认为重新强调在格式说明符中指定精度时通过这些步骤发生的精度损失非常重要(即 7.7375487 变为 7.74 )!通常,使用精度说明符可能不是一个好主意,除非在创建不用于进一步处理(即永远不会被解析)的可读字符串(例如用于摘要文件输出)时。当然,这否定了此Q / A的要点,但需要在此处提及。

Lastly, I think it's important to re-emphasize the loss of precision that occurs through these steps when specifying precision in the format specifier (i.e. 7.7375487 becomes 7.74)! In general using the precision specifier is probably a bad idea except when creating 'readable' strings (e.g. for 'summary' file output) that are not meant for further processing (i.e. will never be parsed). This, of course, negates the point of this Q/A but needs to be mentioned here.

这篇关于在Python中反转C样式格式字符串(`%`)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆