Python 格式字符串“}”充满

发布于 2024-08-16 06:57:41 字数 626 浏览 4 评论 0原文

Python 2.6 定义了 str.format(…),从 Python 3.0 开始,它优于旧的 % 字符串格式样式。然而,查看“迷你语言” ,看来不能用}字符作为填充字符。

对我来说,这似乎是一个奇怪的遗漏。是否有可能以某种方式转义该字符并将其用作填充字符?

我知道我可以填充一些唯一的字符串字符,然后使用 str.replace 或任何其他类似的技巧来实现相同的结果,但这对我来说感觉像是一种黑客攻击…

编辑:我追求的是类似的东西

>>> "The word is {0:}<10}".format("spam")
'The word is spam}}}}}}'

Python 2.6 defines str.format(…), which, from Python 3.0, is preferred to the old % style of string formatting. Looking at the "mini-language", however, it seems that it is impossible to use the } character as a fill character.

This seems like a strange omission to me. Is it possible to somehow escape that character and use it as a fill character?

I know I could fill with some unique-to-the-string character and then use str.replace, or any number of other similar tricks to achieve the same result, but that feels like a hack to me…

Edit: What I'm after is something like

>>> "The word is {0:}<10}".format("spam")
'The word is spam}}}}}}'

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

痴情换悲伤 2024-08-23 06:57:41

您始终可以将其指定为单独的参数,如下所示:

>>> "The word is {0:{1}<10}".format("spam", "}")
'The word is spam}}}}}}'

看,它被传入并用于代替 {1}。

You could always specify it as a separate parameter like so:

>>> "The word is {0:{1}<10}".format("spam", "}")
'The word is spam}}}}}}'

See, it gets passed in and used in place of {1}.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文