Does Python do variable interpolation similar to “string #{var}” in Ruby?

后端 未结 9 1153
盖世英雄少女心
盖世英雄少女心 2020-12-08 06:37

In Python, it is tedious to write:

print \"foo is\" + bar + \'.\'

Can I do something like this in Python?

print \"foo is #{ba

相关标签:
9条回答
  • 2020-12-08 07:34

    Python 3.6 has introduced f-strings:

    print(f"foo is {bar}.")
    

    Old answer:

    Since version 3.2 Python has str.format_map which together with locals() or globals() allows you to do fast:

    Python 3.3.2+ (default, Feb 28 2014, 00:52:16) 
    >>> bar = "something"
    >>> print("foo is {bar}".format_map(locals()))
    foo is something
    >>> 
    
    0 讨论(0)
  • 2020-12-08 07:35

    Yes, absolutely. Python, in my opinion, has great support for string formatting, replacements and operators.

    This might be helpful:
    http://docs.python.org/library/stdtypes.html#string-formatting-operations

    0 讨论(0)
  • 2020-12-08 07:39

    String formatting

    >>> bar = 1
    >>> print "foo is {}.".format(bar)
    foo is 1.
    
    0 讨论(0)
提交回复
热议问题