【问题标题】:Custom string interpolation in PythonPython中的自定义字符串插值
【发布时间】:2020-04-13 10:01:49
【问题描述】:

我想创建一个自定义 f 字符串。例如,CPT 插值器总是将其格式化的内容转换为大写字母:

a = "World"
normal_f_string = f"Hello {a}" # "Hello World"
my_custom_interpolator = CPT"Hello {a}" # "Hello WORLD"

【问题讨论】:

  • 为什么要这样做?
  • @abhiarora 我有一个类实现了 shell 和 Python 之间的桥梁。我想创建像sh"echo {var}" 这样引用给定变量、运行命令并返回标准输出、标准错误和返回代码的东西。

标签: python string formatting format f-string


【解决方案1】:

我在Trigger f-string parse on python string in variable 上找到了答案。具体来说,这里是适应我的问题的代码:

from string import Formatter
import sys

def idem(x):
    return x

_conversions = {'a': ascii, 'r': repr, 's': str, 'e': idem}
# 'e' is new, for cancelling capitalization. Note that using any conversion has this effect, e is just doesn't do anything else.

def z(template, locals_=None):
    if locals_ is None:
        previous_frame = sys._getframe(1)
        previous_frame_locals = previous_frame.f_locals
        locals_ = previous_frame_locals
        # locals_ = globals()
    result = []
    parts = Formatter().parse(template)
    for part in parts:
        literal_text, field_name, format_spec, conversion = part
        if literal_text:
            result.append(literal_text)
        if not field_name:
            continue
        value = eval(field_name, locals_) #.__format__()
        if conversion:
            value = _conversions[conversion](value)
        if format_spec:
            value = format(value, format_spec)
        else:
            value = str(value)
        if not conversion:
            value = value.upper() # Here we capitalize the thing.
        result.append(value)
    res = ''.join(result)
    return res

# Usage:

a = 'World'
b = 10
z('Hello {a} --- {a:^30} --- {67+b} --- {a!r}')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-02
    • 1970-01-01
    • 1970-01-01
    • 2012-01-21
    相关资源
    最近更新 更多