英文:
How to force at least N digits in Python (Numpy)
问题
我要翻译的内容:
假设我们有一个任意的整数,x。我想将这个数字转换为一个字符串;使用 str(x) 很容易实现。
在numpy中,将数字转换为除了十进制以外的其他进制也很容易,使用 np.base_repr(x, base)。但是,如果我想要至少有 N 位数字,该怎么办?例如,如果数字是 0,base_repr 将只输出 0。但是如果我想要至少5位数字,例如 00000 呢?
我尝试了 np.base_repr 函数中的填充设置,但似乎它会左侧附加额外的零,而不是添加它们以适应。例如,np.base_repr(2, base=2, padding=3) 会产生 00010,而不是期望的 010。
我知道这可以手动实现。我们只需在字符串上附加零(左侧附加)直到长度达到 N。但是在numpy中,或者其他一些流行的库中,是否有一个库函数可以实现这个功能?
英文:
Let's say we have an arbitrary integer, x. I want to convert this number to a string; which is pretty easy using str(x).
Converting the number to a different base other than base 10 can be done easily in numpy using np.base_repr(x, base). But how do I force this to have at least N digits; if the number is 0 for example, base_repr will output just 0. But what if I want at least 5 digits, 00000?
I tried the padding setting in the np.base_repr function, but this seems to left-append extra zeroes, instead of adding them to fit. For example, np.base_repr(2, base=2, padding=3) yields 00010 instead of the desired 010.
I know this is possible manually. We can just append zeroes to our string (left-append) until the length is N. But is there a library function in numpy, or some other popular library, that does the trick?
答案1
得分: 1
f"{2:03b}" # 或者:
f"{2:b}".zfill(3)
## '010'
b 代表二进制
f 代表浮点数
:3 强制使用3个位置,但填充会用空格。
:03 强制用零填充。
f"{2:03}"
## '002'
对于不同的进制,可以使用:
np.base_repr(2, base=2).zfill(3)
或者:
f"{np.base_repr(2, base=3):03}"
英文:
Use f-string abilities or .zfill() string method for this:
f"{2:03b}" # or:
f"{2:b}".zfill(3)
## '010'
b is for binary
f would be for float
:3 would enforce 3 positions, however, padding would be with .
:03 enforces padding with zeros.
f"{2:03}"
## '002'
For different bases use:
np.base_repr(2, base=2).zfill(3)
or:
f"{np.base_repr(2, base=3):03}"
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论