【问题标题】:How to get string from a django.utils.safestring.SafeText如何从 django.utils.safestring.SafeText 获取字符串
【发布时间】:2016-11-23 05:38:07
【问题描述】:

我在单元测试中得到了 django.utils.safestring.SafeText:

ipdb> mail.outbox[0].body
u'Dear John Doe,<br>\n<p>\nYou have received a ..

ipdb> type(mail.outbox[0].body)
<class 'django.utils.safestring.SafeText'>

我想将上面的内容转换成一个字符串,这样我就可以去掉\n 字符.. 即我想使用rstrip() 方法.. 但我显然不能在@ 987654324@ 对象。想法?

【问题讨论】:

  • 通过django.utils.encoding.force_text?
  • force_text 不起作用

标签: python django python-2.7


【解决方案1】:

从 Django 2.0.4 开始,str(mail.outbox[0].body) 不再有效——它返回相同的 SafeText 对象。 (请参阅this Django commit 了解原因。)

相反,您可以添加一个空字符串来获取一个常规字符串:

type(mail.outbox[0].body + "") == str

如果它对其他人有帮助,我遇到了这个问题,因为我试图将 SafeText 从 Django 传递到 pathlib.Path,这会引发 TypeError: can't intern SafeText。添加一个空字符串可以修复它。

【讨论】:

    【解决方案2】:

    基于 SafeText 创建新字符串

    str(mail.outbox[0].body)
    

    【讨论】:

      【解决方案3】:

      您可以使用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'>
      

      【讨论】:

      • 这适用于python命令行..但它在实际代码中不起作用
      猜你喜欢
      • 1970-01-01
      • 2021-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-30
      • 2017-07-28
      • 2012-07-23
      • 1970-01-01
      相关资源
      最近更新 更多