How to format raw string with different expressions inside?(如何用不同的表达式格式化原始字符串?)
问题描述
比方说,我们想用正则表达式捕捉一些东西,使用 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.
这篇关于如何用不同的表达式格式化原始字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何用不同的表达式格式化原始字符串?
- 如何在 python3 中将 OrderedDict 转换为常规字典 2022-01-01
- pytorch 中的自适应池是如何工作的? 2022-07-12
- python check_output 失败,退出状态为 1,但 Popen 适用于相同的命令 2022-01-01
- 如何在 Python 的元组列表中对每个元组中的第一个值求和? 2022-01-01
- 如何将一个类的函数分成多个文件? 2022-01-01
- python-m http.server 443--使用SSL? 2022-01-01
- padding='same' 转换为 PyTorch padding=# 2022-01-01
- 分析异常:路径不存在:dbfs:/databricks/python/lib/python3.7/site-packages/sampleFolder/data; 2022-01-01
- 使用Heroku上托管的Selenium登录Instagram时,找不到元素';用户名'; 2022-01-01
- 沿轴计算直方图 2022-01-01
