简体   繁体   English

使用列表范围的 Python 格式化字符串

[英]Python formatted string using list range

I have been researching a lot of questions about It on stackOverflow and google.我在 stackOverflow 和 google 上研究了很多关于 It 的问题。 But none of then solved my problem.但是没有一个解决了我的问题。

Let's say, I have an irregular length string (like a phone number or specific and territorial documents) for example:比方说,我有一个不规则长度的字符串(如电话号码或特定和领土文件),例如:

docA="A123B456"
docB="A123B456CD"
docC="6CD"

I'm writing a function to print documents.我正在编写一个函数来打印文档。 But they don't have a definite pattern, my approach was to use a default variable using the most common pattern and give the responsibility of corner cases to the programmer.但是他们没有明确的模式,我的方法是使用最常见的模式使用默认变量,并将极端情况的责任交给程序员。 eg:例如:

def printDoc(text, pattern="{}{}{}{}#{}{}{}-{}")
    print(pattern.format(*text))

But It would be much more clean and explicit if there's a way to simplify the pattern like但是,如果有一种方法可以简化模式,例如

def printDoc(text, pattern="{0:3}#{4:-1}-{-1}")
    print(pattern.format(*text))

Then I could use It like:然后我可以像这样使用它:

printDoc(docA)
printDoc(docB)
printDoc(docC, "{0:1}-{2}")

But It's not a valid syntax.但这不是有效的语法。 Is there a way of doing this properly?有没有办法正确地做到这一点?

If my approach is wrong, is there a better way of doing this?如果我的方法是错误的,有没有更好的方法来做到这一点?

You could use regular expression to parse the indexes/slices from the format string and use those to index given text.您可以使用正则表达式来解析格式字符串中的索引/切片,并使用它们来索引给定的文本。 You'd also have to remove the indeces from format string before using it with str.format .在将它与str.format一起使用之前,您还必须从格式字符串中删除str.format The only tricky part is actually getting format parameters out from text but if you consider eval acceptable you could do following:唯一棘手的部分实际上是从text获取格式参数,但如果您认为eval可以接受,您可以执行以下操作:

import re

def printDoc(text, pattern="{0:3}#{4:-1}-{-1}"):
    params = []

    # Find occurrences of '{}' from format string and extract format parameter
    for m in re.finditer(r'\{([-:\d]+)\}', pattern):
        params.append(eval('text[{}]'.format(m.group(1))))

    # Remove indeces from format string
    pattern = re.sub(r'\{([-:\d]+)\}', '{}', pattern)
    print(pattern.format(*params))

printDoc('A123B456')

Output:输出:

A12#B45-6

Note that using eval is generally considered bad and unsafe practice .请注意,使用eval通常被认为是不好的和不安全的做法 Although the potential risks are limited here because of restricted character set given to eval you might want to consider other alternatives unless you're the one who controls the format strings.尽管这里的潜在风险是有限的,因为给eval字符集受到限制,但您可能需要考虑其他替代方案,除非您是控制格式字符串的人。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM