How to format raw string with different expressions inside?

为君一笑 提交于 2019-11-29 09:37:41

问题


Let's say, we want to catch something with regex, using rawstring to define the pattern, which pattern has repeating elements, and variables inside. And we also want to use the format() string formatting form. How to do this?

import re
text = '"""!some text'
re.findall(r'"{3}{symbol}some\stext'.format(symbol='!'), text)

But this line leads us to an IndexError:

# IndexError: tuple index out of range

So, my question is: how to format a raw string if it has formatting curly-braces expression, and repeating curly-braces expression inside?

Thanks in advance!


回答1:


Escape the curly brackets with curly brackets

>>> import re
>>> text = '"""!some text'
>>> re.findall(r'"{{3}}{symbol}some\stext'.format(symbol='!'), text)
['"""!some text']

However it is better to just use % formatting in this situation.




回答2:


Use f-strings (python 3)

a = 15
print(fr'Escape is here:\n but still {a}')

# => Escape is here:\n but still 15


来源:https://stackoverflow.com/questions/16754594/how-to-format-raw-string-with-different-expressions-inside

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!