Bin Chen
Bin Chen

Reputation: 63359

django: how to get a substring from django.utils.safestring.SafeUnicode

I noticed django use this to process the string, but can I get a substring from django.utils.safestring.SafeUnicode?

Upvotes: 0

Views: 1929

Answers (2)

gladysbixly
gladysbixly

Reputation: 2659

Yes, you can. Just treat SafeUnicode as a normal string -- to get a substring, take a slice. The slice will have type unicode (not SafeUnicode!); if you want to make it a SafeUnicode string, just make a new one based on the slice:

>>> from django.utils.safestring import SafeUnicode
>>> su = SafeUnicode("This is my original <strong>Safe string</strong>")
>>> just_the_strong = SafeUnicode(su[20:])
>>> print just_the_strong
u'<strong>Safe string</string>'
>>> type(just_the_strong)
<class 'django.utils.safestring.SafeUnicode'>

Upvotes: 1

samplebias
samplebias

Reputation: 37919

You should be able to slice it, or use any of the other methods of unicode:

from django.utils import safestring

x = safestring.SafeUnicode(u'\u2018hi there\u2018')
print repr(x[:3])
u'\u2018hi'

Upvotes: 0

Related Questions