【问题标题】:How can I change numbers font in time library?如何更改时间库中的数字字体?
【发布时间】:2021-01-13 01:02:06
【问题描述】:

我想用 me 数字更改 %H 和 %M 中的数字字体,并在输出时显示 me 数字而不是通常的数字字体 (1,...,9)。如果有人知道解决方案是什么,我会很高兴帮助我解决我的问题。非常感谢。

import time
me = (₀, ₁, ₂, ₃, ₄, ₅, ₆, ₇, ₈, ₉, ₁₀)
HM = time.strftime("%H:%M")

【问题讨论】:

  • 在 Python 和大多数其他编程语言中,数字(数字字符)——像所有其他字符一样——没有与之关联的字体,它们只是 Unicode 代码点(在 Python 3.x 中) .

标签: python time numbers bots telethon


【解决方案1】:

你需要创建一个dict,然后你就可以用你自己的选择替换数字了。

import time
dictionary = {
    '0' : '₀', '1' : '₁', '2' : '₂', '3' : '₃', '4': '₄',
    '5' : '₅', '6' : '₆', '7' : '₇', '8' : '₈', '9' : '₉' 
}

HM = time.strftime("%H:%M")
for key, value in dictionary.items():
    HM = HM.replace(key,value)

【讨论】:

  • 虽然这样可以,但是遍历字典并替换HM的值10次是非常低效的。
【解决方案2】:

文本字符在 Python 中没有与之关联的字体,它们只是 unicode 代码点。但是,听起来您真正想做的是将time.strftime() 返回的字符串中的实际数字字符更改为另一个集合。

最有效的方法可能是创建一个转换表,使用str.maketrans() class 方法将数字字符映射到您想要使用的字符,然后将其传递为str.translate() instance 方法的参数来进行转换。

这里是如何做到这一点。 请注意,您只需构建一次转换表,它可以反复使用多次。

import string
import time

me = '₀₁₂₃₄₅₆₇₈₉'
xlate_tbl = str.maketrans(string.digits, me)  # Create translation table.

HM = time.strftime("%H:%M")
print(HM)
print(HM.translate(xlate_tbl))  # Translate result.

样本输出:

17:42
₁₇:₄₂

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-02
    • 1970-01-01
    • 1970-01-01
    • 2011-06-27
    相关资源
    最近更新 更多