简体   繁体   中英

Python formatted string using list range

I have been researching a lot of questions about It on stackOverflow and google. 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 . The only tricky part is actually getting format parameters out from text but if you consider eval acceptable you could do following:

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 . 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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