如何使用正则表达式格式化 f 字符串? [英] How to format f-strings with regex expressions?

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

问题描述

我有一些字符串,它们最初用加号连接并包含正则表达式字符串.举个例子:

I have a few strings that were originally concatenated with plus signs and included regex strings. Here's an example:

"Level 4: " + re.sub(r"(\w)([A-Z])", r"\1 \2", talents[1]) + "\n\n"

但是,我一直想使用更合适的格式.我对 f 弦做了一些研究,我想在这里使用它们.我是这样试的:

But, I've been meaning to use more proper formatting. I did some research on f-strings and I want to use them here. I tried it this way:

f'Level 4: {re.sub(r"(\w)([A-Z])", r"\1 \2", talents[1])} \n\n'

然而,我的编辑对我咆哮说表达式片段带有反斜杠.在这种情况下,f-strings 不是适合这项工作的工具吗?

However, my editor is barking at me about expression fragments having backslashes. Are f-strings not the right tool for the job in this case?

按照@jwodder 的要求,这是我从 Python 中得到的错误(我使用的是 3.6)

As requested by @jwodder, here is the error I'm getting from Python (I'm on 3.6)

SyntaxError: f-string expression part cannot include a backslash

推荐答案

您不能在 f 字符串中插入带有反斜杠的表达式,目前是 设计限制.您可以将其分为两个语句:

You cannot interpolate an expression with backslash in an f-string, and this is currently a restriction by design. You could separate this into two statements:

subst = re.sub(r"(\w)([A-Z])", r"\1 \2", talents[1])
msg = f'Level 4: {subst} \n\n'

(旁注:目前有一个提案(PEP 536)放宽这种限制使原始代码按预期工作,但尚未接受或实施.)

(Side note: There is currently a proposal (PEP 536) to relax such restriction to make the original code work as expected, but it is not accepted or implemented yet.)

这篇关于如何使用正则表达式格式化 f 字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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