2016-06-25 28 views
1

我有一个代码库通过正在使用的Django smart_str方法:有没有办法用Python原生解决方案替换Django的smart_str?

for p in pro: 
     print smart_str(p["title"]) 

我想用原来的Python的解决方案来替代它,而不里面涉及Django的,但我不知道什么smart_str究竟做:

关于Python 3. smart_bytes的

smart_str(s, encoding='utf-8', strings_only=False, errors='strict')

()的别名上Python 2和smart_text()此 函数返回一个STR或懒惰字符串。

smart_bytes(s, encoding='utf-8', strings_only=False,errors='strict')

返回s的字节串的版本,编码 如在编码指定。

如果strings_only为True,则不要转换(某些)非类字符串的对象。

我们可以用print unicode(u'\xa1').encode("utf-8")来代替吗?

+0

这是*“Python自身” *请参阅[源代码](https://github.com/django/django/blob/92053acbb9160862c3e743a99ed8ccff8d4f8fd6/django/utils/encoding.py)。它处理的事件多于您建议的替代方案。 – jonrsharpe

+0

我明白了,所以我只是将'smart_byte'和'force_byte'函数的代码复制为独立于django –

+0

此外,您还需要实现(或至少提供一个虚拟)'django.utils.functional.Promise'按原样使用它们。 – jonrsharpe

回答

3

我与适用unicode(x).encode("utf-8")如果字符串是unicode,并将其转换为str这个虚拟函数代替它,如果它是一个数字:

def smart_str(x): 
    if isinstance(x, unicode): 
     return unicode(x).encode("utf-8") 
    elif isinstance(x, int) or isinstance(x, float): 
     return str(x) 
    return x 
+0

没问题,但是'smart_str'做的比这个更多... – Renaud

+1

我知道,那就是这个项目所需要的 –

相关问题