问题描述
我是 Python 新手。
我一直在弄清楚 const useUnload = fn => {
const cb = useRef(fn); // init with fn,so that type checkers won't assume that current might be undefined
useEffect(() => {
cb.current = fn;
},[fn]);
useEffect(() => {
const onUnload = () => {
cb.current();
};
window.addEventListener("beforeunload",onUnload);
return () => window.removeEventListener("beforeunload",onUnload);
},[]);
};
的工作原理
示例 1
fstring
输出:
for n in range(1,11):
sentence = f"The value is {n:{n:1}}"
print(sentence)
示例 2
The value is 1
The value is 2
The value is 3
The value is 4
The value is 5
The value is 6
The value is 7
The value is 8
The value is 9
The value is 10
输出:
for n in range(1,11):
sentence = f"The value is {n:{n:02}}"
print(sentence)
示例 3
The value is 1
The value is 02
The value is 003
The value is 0004
The value is 00005
The value is 000006
The value is 0000007
The value is 00000008
The value is 000000009
The value is 10
输出:
for n in range(1,11):
sentence = f"The value is {n:{n:03}}"
print(sentence)
我真正想知道的是
The value is 1
The value is 02
The value is 003
The value is 0004
The value is 00005
The value is 000006
The value is 0000007
The value is 00000008
The value is 000000009
The value is 0000000010
如何解释宽度和精度?
为什么示例 2 最后一个循环没有用零填充计算?
如果我没记错的话,示例 1 的输出被解释为宽度。 示例 2 和示例 3 填充零。
fstring
解决方法
你可以这样做:
monthnumber
for n in range(1,11):
n = f'{n:0>2}'
sentence = f"The value is {n:>5}"
print(sentence)
表示如果 n 的数字小于 2,则在前面填充零,而 {n:0>2}
表示在 n 前面填充 5 个空格。
见Python f-string Documentation
for n in range(1,11):
sentence = f"The value is {n:02}"
print(sentence)
您可以将 {n:02} 更改为 {n:03} 或其他以检查差异。
{n:0x} 打印十六进制格式。