-2

我正在尝试创建一个 dict 执行以下操作

data = {
    'date': kwargs['this_number'],
    'Number': kwargs['number'],
}

但是,当我打印数据时,即

print(data)

我得到以下结果:

{
    'date': datetime.date(2018, 9, 30),
    'Number': u'4929000000006'
}

我的问题是,为什么要添加 Djangodatetime.date(等等u,我该如何摆脱它们?我需要 POST 的原始数据

4

2 回答 2

2

在 python 2.xa 中u表示它是一个 unicode 对象,但它与字符串对象非常相似,要将其转换为原始数据,只需使用str()方法或int()方法

>>> type(u'K-DawG')
<type 'unicode'>

>>> type('K-DawG')
<type 'str'>

>>> type(str(u'K-DawG'))
<type 'str'>

但是在 python 3.x中,一个 unicode 对象被视为一个string,所以在你的情况下,一个int()方法就是转换被认为是一个字符串的数字所需要的全部

>>> type(u'K-DawG')
<class 'str'>

>>> type(int(u'12'))
<class 'int'>

要将日期作为字符串而不是作为datetime.date对象获取,请使用以下.isoformat()方法:

data = {
    'date': datetime.date(2018, 9, 30).isoformat(),
    'Number': int(u'4929000000006'),
}
print(data)

这将打印:{'Number': 4929000000006, 'date': '2018-09-30'}

注意:我直接使用datetime.date(2018, 9, 30)而不是kwargs['this_number']因为,您没有说明更多信息或没有暴露更多需要的代码,我所说的必须足够

于 2013-09-20T14:03:54.857 回答
1

当您打印字典时,它的项目不是str-ified 而是repr-ified。这是有充分理由的;如果它被str-ified 那么{"foo", "22"}将打印为{foo: 22}!

您可以通过手动打印字典来解决此问题:

import datetime

my_dict = {'date': datetime.date(2018, 9, 30),'Number': u'4929000000006'}

def substring(item):
    if isinstance(item, unicode):
        return repr(item)[1:]

    if isinstance(item, datetime.date):
        return repr(str(item))

    return repr(item)

def dict_substrings(dict):
    yield u"{"

    if my_dict:
        nameitems = my_dict.iteritems()
        name, item = next(nameitems)

        yield substring(name)
        yield u": "
        yield substring(item)

        for name, item in nameitems:
            yield u", "

            yield substring(name)
            yield u": "
            yield substring(item)

    yield u"}"

def dict_representation(dict):
    return "".join(dict_substrings(dict))

print(dict_representation(my_dict))

关键功能是substring您应该手动修改以按照您想要的方式输出内容。为了保持效率,它有点啰嗦O(n)

于 2013-09-20T14:21:17.043 回答