您可以使用django.utils.safestring.SafeText 对象做您想做的事情。您可以将几乎所有方法作为字符串应用到 SafeText 对象上。可用的方法是
'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'islower', 'isnumeric', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill'
但它们会返回 unicode 对象。示例:-
>>> from django.utils.safestring import SafeText
>>> my_safe_text = SafeText('Dear John Doe,<br>\n<p>\nYou have received a .. ')
>>> type(my_safe_text)
<class 'django.utils.safestring.SafeText'>
>>> my_replaced_unicode = my_safe_text.replace('\n','')
>>> my_replaced_unicode
u'Dear John Doe,<br><p>You have received a .. '
>>> type(my_replaced_unicode)
<type 'unicode'>
>>> my_rstriped_unicode = my_safe_text.rstrip()
>>> my_rstriped_unicode
u'Dear John Doe,<br>\n<p>\nYou have received a ..'
>>> type(my_rstriped_unicode)
<type 'unicode'>