为什么Python中没有Inf、Inf和NaN关键字?

2024-04-23 17:36:43 发布

您现在位置:Python中文网/ 问答频道 /正文

PEP 754的拒绝通知中,声明:

This PEP has been rejected. After sitting open for four years, it has failed to generate sufficient community interest.

Several ideas of this PEP were implemented for Python 2.6. float('inf') and repr(float('inf')) are now guaranteed to work on every supported platform with IEEE 754 semantics. However the eval(repr(float('inf'))) roundtrip is still not supported unless you define inf and nan yourself:

>>> inf = float('inf')
>>> inf, 1E400
(inf, inf)
>>> neginf = float('-inf')
>>> neginf, -1E400
(-inf, -inf)
>>> nan = float('nan')
>>> nan, inf * 0.
(nan, nan)

这似乎说明Python中没有对Inf、NaN和-Inf的本机支持,并且提供的示例是准确的!但是,这是不必要的冗长:

$ python2.7
>>> 1e400
inf
>>> 1e400 * 0
nan
>>> -1e400 * 0
nan
>>> -1e400
-inf
$ python3
>>> 1e400
inf
>>> 1e400 * 0
nan
>>> -1e400 * 0
nan
>>> -1e400
-inf

这些是数字1*10^400的正则表示。默认情况下,infnan在语法中不存在,但是如果它们存在于表示中,那么inf和{}关键字就不存在了?在

我不是在问政治公众人物为什么会被拒绝,因为这是基于意见的。在


Tags: andto声明fornanfloatthispep
1条回答
网友
1楼 · 发布于 2024-04-23 17:36:43

最好使用Matcher.appendReplacement/Matcher.appendTail解决此问题,如下所示:

String input = "hello byte world";

Pattern p = Pattern.compile("(\\w+) (\\w+) (\\w+)");
Matcher m = p.matcher(input);

StringBuffer sb = new StringBuffer();
while (m.find()) {

    // Compute replacement for middle word
    String w = m.group(2);
    String s = w.equals("byte") ? "<A BYTE!>"
             : w.equals("word") ? "<A WORD!>"
             : "something else";

    m.appendReplacement(sb, "$1 " + s + " $3");
}
m.appendTail(sb);
System.out.println(sb);

输出:

hello <A BYTE!> world

相关问题 更多 >