【问题标题】:How to add an input numbers on dictionary?如何在字典上添加输入数字?
【发布时间】:2022-01-09 09:46:21
【问题描述】:

我是 python 新手。我尝试了不同的方法来为我的代码添加值。在这段代码中,我有 2 个问题。

  • 我需要使用输入的数字(例如 0400 或 0352)添加到字典中
  • 输入数字转换为时间(例如 4:00 或 3:52)。
employee1_data = {};
    
def login_time_admin_a():  
        while True:
            print("""
            ==============================
            | PLEASE ENTER YOUR INFO     |
            ==============================
                """)
            time=input("ENTER TIME: ")
            if time.isalpha():
                print("""
                ======================
                | INCORRECT INPUT    |
                ======================
                """)
                continue
            date = input("ENTER DATE: ")
            if date.isalpha():
                print("""
                ======================
                |  INCORRECT INPUT   |
                ======================
                """)
                continue
            else:
                print("""
                    ============================
                    | THANK YOU FOR LOGGING IN |
                    ============================
                    """)
                employee1_data[time] = time()
                employee1_data[date] = date()

【问题讨论】:

  • 您面临的具体问题是什么?你不能输入一个字符串然后用time()“调用”它似乎问题根本不是在dict中添加,而是将frmo字符串转换为日期
  • 这能回答你的问题吗? Convert string into datetime.time object

标签: python dictionary if-statement time type-conversion


【解决方案1】:

根据the documenatation

>>> employee1_data = {}
>>> employee1_data['this_key_001']='this_value_001'
>>> print(employee1_data['this_key_001'])
this_value_001
>>> employee1_data['use the input numbers']=int('0400')
>>> print(employee1_data['use the input numbers'])
400
>>> employee1_data['use the input numbers']=str('0400')
>>> print(employee1_data['use the input numbers'])
0400

您可以对时间数据使用相同的方法,也可以使用特殊格式的数据或字符串...

data = (1)
format_string = "Your current balance is $%s."
print(format_string % data)
...
Your current balance is $1.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-06
    • 2020-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-18
    相关资源
    最近更新 更多