Is there a Python equivalent to Ruby's string interpolation?

前端 未结 9 1191
攒了一身酷
攒了一身酷 2020-11-22 17:04

Ruby example:

name = \"Spongebob Squarepants\"
puts \"Who lives in a Pineapple under the sea? \\n#{name}.\"

The successful Python string co

9条回答
  •  半阙折子戏
    2020-11-22 17:47

    import inspect
    def s(template, **kwargs):
        "Usage: s(string, **locals())"
        if not kwargs:
            frame = inspect.currentframe()
            try:
                kwargs = frame.f_back.f_locals
            finally:
                del frame
            if not kwargs:
                kwargs = globals()
        return template.format(**kwargs)
    

    Usage:

    a = 123
    s('{a}', locals()) # print '123'
    s('{a}') # it is equal to the above statement: print '123'
    s('{b}') # raise an KeyError: b variable not found
    

    PS: performance may be a problem. This is useful for local scripts, not for production logs.

    Duplicated:

    • Python string formatting: % vs. .format

    • What is the Python equivalent of embedding an expression in a string? (ie. "#{expr}" in Ruby)

    • What is Ruby equivalent of Python's `s= "hello, %s. Where is %s?" % ("John","Mary")`

    • Is there a Python equivalent to Ruby's string interpolation?

提交回复
热议问题