【问题标题】:python how to convert from string.template object to stringpython如何从string.template对象转换为字符串
【发布时间】:2011-11-28 07:16:26
【问题描述】:

这很简单。我确定我错过了一些愚蠢的东西。

fp = open(r'D:\UserManagement\invitationTemplate.html', 'rb')        
html = Template(fp.read())
fp.close()
html.safe_substitute(toFirstName='jibin',fromFirstName='Vishnu')
print html 

当我直接在解释器中运行这段代码时,我得到了正确的输出。 但是当我从文件中运行它时。我得到<string.Template object at 0x012D33B0>。如何从字符串转换。模板对象到字符串。我试过str(html)。再见不是打印语句应该这样做(字符串转换) ?

【问题讨论】:

    标签: python string templates


    【解决方案1】:

    safe_substitute 返回,作为字符串,带有替换的模板。这样,您可以重复使用相同的模板进行多次替换。所以你的代码必须是

    print html.safe_substitute(toFirstName='jibin',fromFirstName='Vishnu')
    

    【讨论】:

      【解决方案2】:

      根据the docs你应该取safe_substitute的返回值

      fp = open(r'D:\UserManagement\invitationTemplate.html', 'rb')        
      html = Template(fp.read())
      fp.close()
      result = html.safe_substitute(toFirstName='jibin',fromFirstName='Vishnu')
      print result 
      

      【讨论】:

        【解决方案3】:

        结果由 safe_substitute 方法返回:

        result = html.safe_substitute(toFirstName='jibin',fromFirstName='Vishnu')
        print result
        

        【讨论】:

          猜你喜欢
          • 2013-10-24
          • 1970-01-01
          • 2011-12-12
          • 1970-01-01
          • 2021-08-03
          • 2016-02-27
          • 2021-12-07
          • 2021-02-03
          • 1970-01-01
          相关资源
          最近更新 更多