Python类型转换

Dav*_*ave 10 python int types

什么是在python中将int's,long's,double's转换为字符串,反之亦然的最佳方法.

我循环遍历列表并将long传递给应该转换为unicode字符串的dict.

我做

for n in l:  
    {'my_key':n[0],'my_other_key':n[1]}
Run Code Online (Sandbox Code Playgroud)

为什么一些最明显的事情如此复杂?

Mar*_*ers 37

要从数字类型转换为字符串:

str(100)
Run Code Online (Sandbox Code Playgroud)

要从字符串转换为int:

int("100")
Run Code Online (Sandbox Code Playgroud)

要从字符串转换为float:

float("100")
Run Code Online (Sandbox Code Playgroud)


And*_*Dog 2

你可以在 Python 2.x 中这样做:

>>> l = ((1,2),(3,4))
>>> dict(map(lambda n: (n[0], unicode(n[1])), l))
{1: u'2', 3: u'4'}
Run Code Online (Sandbox Code Playgroud)

或者在 Python 3.x 中:

>>> l = ((1,2),(3,4))
>>> {n[0] : str(n[1]) for n in l}
{1: '2', 3: '4'}
Run Code Online (Sandbox Code Playgroud)

请注意,Python 3 中的字符串与 Python 2 中的 unicode 字符串相同。