将空数字类型转换为格式说明符

发布于 2025-01-05 07:30:42 字数 751 浏览 2 评论 0原文

有没有什么方法可以将“空”数字类型传递到数字格式说明符中,并让它打印与该说明符关联的空格?

IE。

n = "Scientific:"
v = 123.321
strfmt = "%5.4E"
output = "%s|"+strfmt+"|"
print output % (n, v)

>   Scientific:|1.2332E+02|

v = EMPTY
print output % (n, v)

>   Scientific:|          |

最终目标是处理不完整的行,而无需在循环时自适应更改格式字符串

perline = 3
n = ["1st:","2nd:","3rd:","4th:","5th:","6th:"]
v = [1.0, 2.0, 3.0, 4.0]

strfmt = "%5.4E"
output = ("%s|"+strfmt+"|  ")*perline+"\n"

for args in map(EMPTY,*[iter(n),iter(v)]*perline):
    print output % args

>   1st:|1.0000E+00|  2nd:|2.0000E+00|  3rd:|3.0000E+00|
>   4th:|4.0000E+00|  5th:|          |  6th:|          |

要执行上述代码,我将 EMPTY 替换为 None,尽管当您将 None 传递给格式字符串时会出现错误

Is there any way to pass an "empty" numeric type into a numeric format specifier and have it print the blank space associated with that specifier?

ie.

n = "Scientific:"
v = 123.321
strfmt = "%5.4E"
output = "%s|"+strfmt+"|"
print output % (n, v)

>   Scientific:|1.2332E+02|

v = EMPTY
print output % (n, v)

>   Scientific:|          |

The ultimate goal is to deal with incomplete lines without adaptively changing the format string while looping

perline = 3
n = ["1st:","2nd:","3rd:","4th:","5th:","6th:"]
v = [1.0, 2.0, 3.0, 4.0]

strfmt = "%5.4E"
output = ("%s|"+strfmt+"|  ")*perline+"\n"

for args in map(EMPTY,*[iter(n),iter(v)]*perline):
    print output % args

>   1st:|1.0000E+00|  2nd:|2.0000E+00|  3rd:|3.0000E+00|
>   4th:|4.0000E+00|  5th:|          |  6th:|          |

To execute the above code I replaced EMPTY with None although that gives an error when you pass None to the format string

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

眼前雾蒙蒙 2025-01-12 07:30:42

您将无法仅通过数字格式来完成此操作。你需要一些逻辑:

strfmt = "%5.4E"
v = None

if v in [None, '']:
  output = "%s|          |"
else:
  output = "%s|"+strfmt+"|"

You won't be able to do it with just number formatting. You'll need some logic:

strfmt = "%5.4E"
v = None

if v in [None, '']:
  output = "%s|          |"
else:
  output = "%s|"+strfmt+"|"
暮光沉寂 2025-01-12 07:30:42

简短回答:对于 n 个位置宽的字段,'% n s' % '' 就可以了。也就是说,'%15s' % '' 将打印 15 个空格。

长答案:当您在格式说明符中指定宽度时, 第一个数字是最小宽度整个字段。不过,"%5.4E" 将占据超过 5 个位置,因为仅指数就已经占据了 3 个位置。

指定类似 "%12.4E" 的内容并获得一致的结果。对于缺失值,请指定 "%12s" 并传递空字符串(而不是 None)而不是值。

Short answer: for a field n positions wide, '%​n​s' % '' will do. That is, to '%15s' % '' will print 15 spaces.

Long answer: when you specify a width in format specifiers, the first number is the minimum width of the entire field. "%5.4E" will take more than 5 places, though, because just the exponent will take 3 places already.

Specify something like "%12.4E" and get consistent results. For missing values, specify "%12s" and pass an empty string (not None) instead of the value.

离笑几人歌 2025-01-12 07:30:42

一种选择是将 output 中的数字格式替换为 %s,然后在替换元组中创建正确的数字输出或空白空间,具体取决于 >v 是:

>>> v = 123.321
>>> "%s|%s|" % (n, "%5.4E" % v if v is not None else " "*10)
'Scientific:|1.2332E+02|'
>>> v = None
>>> "%s|%s|" % (n, "%5.4E" % v if v is not None else " "*10)
'Scientific:|          |'

您可以通过一个简单的闭包使其功能更强大:

def make_default_blank_formatter(format, default):
    def default_blank_formatter(v):
        return format % v if v is not None else default
    return default_blank_formatter

scientific_formatter = make_default_blank_formatter("%5.4E", " "*10)

>>> v = 123.321
>>> "%s|%s|" % (n, scientific_formatter(v))
'Scientific:|1.2332E+02|'
>>> v = None
>>> "%s|%s|" % (n, scientific_formatter(v))
'Scientific:|          |'

编辑:以下是您如何重新编写打印代码以使用它:

perline = 3
n = ["1st:","2nd:","3rd:","4th:","5th:","6th:"]
v = [1.0, 2.0, 3.0, 4.0, None, None]

strfmt = "%5.4E"
output = ("%s|%s|  ")*perline

for args in zip(*[iter(n),iter(map(scientific_formatter, v))]*perline):
    print output % args

One option would be to replace the numeric format in output with %s, and then in the replacing tuple create either the correct numeric output or the empty space depending on what v is:

>>> v = 123.321
>>> "%s|%s|" % (n, "%5.4E" % v if v is not None else " "*10)
'Scientific:|1.2332E+02|'
>>> v = None
>>> "%s|%s|" % (n, "%5.4E" % v if v is not None else " "*10)
'Scientific:|          |'

You could make this a little more functional with a simple closure:

def make_default_blank_formatter(format, default):
    def default_blank_formatter(v):
        return format % v if v is not None else default
    return default_blank_formatter

scientific_formatter = make_default_blank_formatter("%5.4E", " "*10)

>>> v = 123.321
>>> "%s|%s|" % (n, scientific_formatter(v))
'Scientific:|1.2332E+02|'
>>> v = None
>>> "%s|%s|" % (n, scientific_formatter(v))
'Scientific:|          |'

edit: Here is how you could rework your printing code to use this:

perline = 3
n = ["1st:","2nd:","3rd:","4th:","5th:","6th:"]
v = [1.0, 2.0, 3.0, 4.0, None, None]

strfmt = "%5.4E"
output = ("%s|%s|  ")*perline

for args in zip(*[iter(n),iter(map(scientific_formatter, v))]*perline):
    print output % args
情场扛把子 2025-01-12 07:30:42

您可以使用 itertools.izip_longestnv 中的项目配对,并使用空字符串填充缺失值。

要获得 v 中的项目的正确格式,您可以使用 strfmt 预先格式化浮点数,并使用类似

output = "%s|%10s|  "

连接 n 中的项目的 方法代码>和<代码>v。通过这种方式,v 中的项目现在都是字符串,包括空字符串,而不是浮点数和空字符串的混合。


import itertools

perline = 3
n = ["1st:", "2nd:", "3rd:", "4th:", "5th:", "6th:"]
v = [1.0, 2.0, 3.0, 4.0]

strfmt = "%5.4E"
v = (strfmt % val for val in v)
output = "%s|%10s|  "

pairs = itertools.izip_longest(n, v, fillvalue = '')
items = (output % (place, val) for place, val in pairs)
for row in zip(*[items]*perline):
    print(''.join(row))

产量

1st:|1.0000E+00|  2nd:|2.0000E+00|  3rd:|3.0000E+00|  
4th:|4.0000E+00|  5th:|          |  6th:|          |  

You could use itertools.izip_longest to pair the items in n and v, and fill in missing values with the empty string.

To get the proper formatting for the items in v, you could pre-format the floats with strfmt, and use something like

output = "%s|%10s|  "

to join the items in n and v. By doing it this way, the items in v are now all strings, including the empty strings, and not a mixture of floats and empty strings.


import itertools

perline = 3
n = ["1st:", "2nd:", "3rd:", "4th:", "5th:", "6th:"]
v = [1.0, 2.0, 3.0, 4.0]

strfmt = "%5.4E"
v = (strfmt % val for val in v)
output = "%s|%10s|  "

pairs = itertools.izip_longest(n, v, fillvalue = '')
items = (output % (place, val) for place, val in pairs)
for row in zip(*[items]*perline):
    print(''.join(row))

yields

1st:|1.0000E+00|  2nd:|2.0000E+00|  3rd:|3.0000E+00|  
4th:|4.0000E+00|  5th:|          |  6th:|          |  
余罪 2025-01-12 07:30:42

如上所述,只需在打印之前将数字转换为字符串,然后用相同长度的空字符串替换缺失的数字。这实际上可以写得非常紧凑,但是我永远不会在严肃的代码中使用它:

from itertools import izip_longest, groupby, chain

perline = 3
n = ["1st:","2nd:","3rd:","4th:","5th:","6th:"]
v = [1.0, 2.0, 3.0, 4.0]

strfmt = "%5.4E"
output = ("%s|%s|  ")*perline

for _, args in groupby(enumerate(chain(*izip_longest(n, (strfmt % x for x in v),
                                                     fillvalue = ' '*len(strfmt % 0)))),
                       lambda (i, v): i/perline/2):
    print output % zip(*args)[1]

最后一个循环的更具可读性和可靠性的版本:

l = ()
for pair in izip_longest(n, (strfmt % x for x in v),
                         fillvalue = ' '*len(strfmt % 0)):
    l += pair
    if len(l) == perline*2:
        print output % l
        l = ()

As suggested above, just convert your numbers to strings before printing, and replace missing numbers with empty strings of the equal length. This can be actually written very compact, however I would never use this in serious code:

from itertools import izip_longest, groupby, chain

perline = 3
n = ["1st:","2nd:","3rd:","4th:","5th:","6th:"]
v = [1.0, 2.0, 3.0, 4.0]

strfmt = "%5.4E"
output = ("%s|%s|  ")*perline

for _, args in groupby(enumerate(chain(*izip_longest(n, (strfmt % x for x in v),
                                                     fillvalue = ' '*len(strfmt % 0)))),
                       lambda (i, v): i/perline/2):
    print output % zip(*args)[1]

More readable and reliable version of the last loop:

l = ()
for pair in izip_longest(n, (strfmt % x for x in v),
                         fillvalue = ' '*len(strfmt % 0)):
    l += pair
    if len(l) == perline*2:
        print output % l
        l = ()
野味少女 2025-01-12 07:30:42

查看响应后,您似乎无法将任何内容传递给数字格式说明符以使其打印与其关联的空格。

有多种方法可以解决此问题,如下所示。就我个人而言,我喜欢 Unutbu 的部分答案。我认为我最终要做的方式是在开始时创建两个格式说明符并使用 Blender 建议的逻辑。

After viewing the responses it appears that there is no thing you can pass to a numeric format specifier to have it print the blank space associated with it.

There are a number of ways to work around this shown below. Personally I liked parts of Unutbu's answer. I think the way I will ultimately do it is create two format specifiers at the beginning and use logic as suggested by Blender.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文