Reputation: 12107
I am passing with a code base that is using the smart_str
method of Django:
for p in pro:
print smart_str(p["title"])
I want to replace it with a native python solution without involving django inside but I am not sure what smart_str
exactly do:
smart_str(s, encoding='utf-8', strings_only=False, errors='strict')
Alias of smart_bytes() on Python 2 and smart_text() on Python 3. This function returns a str or a lazy string.
and
smart_bytes(s, encoding='utf-8', strings_only=False,errors='strict')
Returns a bytestring version of s, encoded as specified in encoding.
If strings_only is True, don’t convert (some) non-string-like objects.
Could we replace it simply with print unicode(u'\xa1').encode("utf-8")
?
Upvotes: 3
Views: 6042
Reputation: 12107
I replaced it with this dummy function that apply unicode(x).encode("utf-8")
if the string is unicode, and convert it to str
if it's a number:
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
Upvotes: 4