python - 我不明白冒号在 str.format 中的作用

标签 python

https://coderbyte.com/information/Division%20Stringified

Have the function DivisionStringified(num1,num2) take both parameters being passed, divide num1 by num2, and return the result as a string with properly formatted commas. If an answer is only 3 digits long, return the number with no commas (ie. 2 / 3 should output "1"). For example: if num1 is 123456789 and num2 is 10000 the output should be "12,346".

这是顶级用户的解决方案,不是我的:

def DivisionStringified(num1, num2): 
    return '{:,}'.format((num1 + (num2 / 2)) / num2)

'{:,}'.format 的作用是什么?我不知道如何将大量逗号放置在正确的位置。

最佳答案

documentation说:

The ',' option signals the use of a comma for a thousands separator. For a locale aware separator, use the 'n' integer presentation type instead.

所以我们可以看到这就是 , 在格式字符串中所做的事情。

对于:,格式字符串的一般格式类似于:

{what:format_spec}

这两部分都是可选的 - 默认格式规范只是 !s (这意味着使用 str 内置格式)。如果没有指定“what”部分,那么 python 只是填充适当的位置参数的位置。在这种情况下,: 是必需的,以便格式解析器可以拾取 format_spec 部分。

关于python - 我不明白冒号在 str.format 中的作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41290837/

相关文章:

Python 性能 : remove item from list

python - 在调用参数之一的成员函数时如何对函数进行单元测试

python - 覆盖图像时 pylab 子图边界发生变化

Python运行shell命令并模拟用户输入

python - 仅在 a 元素中用于 href 的正则表达式

python - 强制 QRubberBand 具有特定的纵横比

python - 返回最长连续的测距整数序列

python - pyunit 的漂亮 html 报告

python - 执行命令时路径未添加到 $PATH 变量

python - 如何在 Django 中获取最后 10 项数据?