如何用不同的表达式格式化原始字符串?
- 作者: 黄某某007
- 来源: 51数据库
- 2022-12-05
问题描述
比方说,我们想用正则表达式捕捉一些东西,使用 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}somestext'.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}somestext'.format(symbol='!'), text)
['"""!some text']
但是在这种情况下最好只使用 % 格式.
However it is better to just use % formatting in this situation.
推荐阅读
热点文章
Discord.py(重写)on_member_update 无法正常工作
0
Discord.py 在 vc 中获取用户分钟数
0
discord.py 重写 |为我的命令出错
0
Discord.py rewrite 如何 DM 命令?
0
播放音频时,最后一部分被切断.如何解决这个问题?(discord.py)
0
在消息删除消息 Discord.py
0
如何使 discord.py 机器人私人/直接消息不是作者的人?
0
(Discord.py) 如何获取整个嵌入内容?
0
Discord bot 尽管获得了许可,但不能提及所有人
0
Discord.py discord.NotFound 异常
0
