Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
290 views
in Technique[技术] by (71.8m points)

python - Format a string that has extra curly braces in it

I have a LaTeX file I want to read in with Python 3 and format a value into the resultant string. Something like:

...
extbf{REPLACE VALUE HERE}
...

But I have not been able to figure out how to do this since the new way of doing string formatting uses {val} notation and since it is a LaTeX document, there are tons of extra {} characters.

I've tried something like:

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

but I get

KeyError: 'This and that'
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Method 1, which is what I'd actually do: use a string.Template instead.

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

Method 2: add extra braces. Could do this using a regexp.

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

(possible) Method 3: use a custom string.Formatter. I haven't had cause to do this myself so I don't know enough of the details to be helpful.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...