2012-02-06 67 views
13

我有一個LaTeX文件,我想用Python 3讀入並將值格式化爲結果字符串。喜歡的東西:格式化一個字符串,其中包含額外的大括號

... 
\textbf{REPLACE VALUE HERE} 
... 

但我一直無法弄清楚如何做到這一點,因爲這樣做字符串格式化的新方式使用{val}符號和,因爲它是一個LaTeX文檔,有噸的額外{}字符。

我已經試過類似:

'\textbf{This and that} plus \textbf{{val}}'.format(val='6') 

,但我得到

KeyError: 'This and that' 

回答

20

方法1,這是我想其實也:使用string.Template代替。

>>> from string import Template 
>>> Template(r'\textbf{This and that} plus \textbf{$val}').substitute(val='6') 
'\\textbf{This and that} plus \\textbf{6}' 

方法2:添加額外的大括號。可以使用正則表達式來做到這一點。

>>> r'\textbf{This and that} plus \textbf{val}'.format(val='6') 
Traceback (most recent call last): 
    File "<interactive input>", line 1, in <module> 
KeyError: 'This and that' 
>>> r'\textbf{{This and that}} plus \textbf{{{val}}}'.format(val='6') 
'\\textbf{This and that} plus \\textbf{6}' 

(可能)方法3:使用自定義string.Formatter。我自己沒有理由這樣做,所以我不知道足夠的細節是否有用。

+0

任何線索string.Template是否會在將來被棄用?新的python 3格式化似乎包含了這一點。對於LaTeX編輯,模板更方便。 – levesque 2013-03-20 19:29:49

+0

@levesque:嗯,從3.4版本開始它一直沒有被廢棄,它提供了不同於'{}'格式化的功能,所以我認爲它會持續一段時間。 – DSM 2013-03-20 19:35:20

+0

可能更好的方法來添加額外的大括號而不是使用正則表達式是'str.translate'。 'unformatter = str.maketrans({'{':'{{','}':'}}'})',然後修復給定的字符串'goodstring = badstring.translate(unformatter)'(注意:問題是關於Python 3.x;在2.x上,這隻適用於'unicode',而不是'str',因爲只有'unicode'支持1-n翻譯映射。) – ShadowRanger 2016-09-23 12:55:52

相關問題