2016-06-25 66 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

我知道,那就是這個項目所需要的 –

相關問題