如何格式化内部具有不同表达式的原始字符串? [英] How to format raw string with different expressions inside?

查看:63
本文介绍了如何格式化内部具有不同表达式的原始字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我们想用regex捕获一些东西,使用rawstring定义模式,该模式内部有重复的元素和变量.而且我们还想使用format()字符串格式格式.该怎么做?

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)

但是这一行将我们引至IndexError:

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?

提前谢谢!

推荐答案

用大括号转义大括号

>>> 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.

这篇关于如何格式化内部具有不同表达式的原始字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆