title: How to replace latex bold command with Word docx equivalent in python?
body: <p>I'm using python 2.7 and <code>python-docx-template</code> to move information from a text file into a docx template. The text is converted to RichText before being placed in the template. </p>
  
  <p>Some lines of text may contain a latex command for bold somewhere in the text. I'm using re.sub() to remove the latex commands, leaving only the word(s) to be bold. That means the word is not in bold in the final docx file. Ideally, I would like to replace the latex commands with the docx commands necessary to make the word bold. </p>
  
  <p>For example, 'Here is a sentence with \textbf{bold words} in the middle of it.'</p>
  
  <p>I've tried replacing the latex with <code>python-docx-template</code>'s <code>rt.add('bold words', bold=True)</code> but it does not translate to RichText when the entire paragraph is converted to RichText. I did not really expect this to work but I tried anyway.</p>
  
  <p>I also tried adding xml commands, <code>&lt;w:r&gt;&lt;w:rPr&gt;&lt;w:b/&gt;&lt;/w:rPr&gt;&lt;w:t xml:space="preserve"&gt; bold words &lt;/w:t&gt;&lt;/w:r&gt;</code>, but this did not work either.</p>
  
  <p>I suspect that I will have to break the string into chunks, then rt.add() them together. If so, I'm not sure how to do this. A string may have more than one latex bold command but most strings will not have any latex commands.</p>
  
  <p>If chunks are necessary, how can I go about doing this? Or, is there an alternative solution?</p>
  
  <p><strong>Edit:</strong></p>
  
  <p>I was able to answer my own question but I would be glad to know of better or more efficient ways to accomplish this task.</p>
  
  <pre><code>from docxtpl import DocxTemplate, RichText
  import re
  
  tpl=DocxTemplate('test_tpl.docx')
  
  startsentence = 'Here is a sentence with \textbf{bold words} in the middle of it.'
  
  latexbold = re.compile(r'\textbf\{([a-zA-Z0-9 .]+)\}')
  
  # Strip the latex command.
  strippedsentence = re.sub(latexbold, '\\1', startsentence)
  rtaddsentence = re.sub(latexbold, 'rt.add(" \\1 ", bold=True)', startsentence)
  docxsentence = re.sub(latexbold, '&lt;w:r&gt;&lt;w:rPr&gt;&lt;w:b/&gt;&lt;/w:rPr&gt;&lt;w:t xml:space="preserve"&gt;\\1&lt;/w:t&gt;&lt;/w:r&gt;', startsentence)
  
  richstrippedsentence = RichText(strippedsentence)
  richrtaddsentence = RichText(rtaddsentence)
  richdocxsentence = RichText(docxsentence)
  
  context = {
      'strippedresult': richstrippedsentence,
      'rtresult': richrtaddsentence,
      'docxresult': richdocxsentence,
  }
  
  tpl.render(context)
  tpl.save('test.docx')
  </code></pre>
  
  <p>Here are the results in Word.</p>
  
  <p><a href="https://i.stack.imgur.com/ei5Uz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ei5Uz.png" alt="Final results"></a></p>