String substitution in Python 3?

后端 未结 4 470
陌清茗
陌清茗 2021-02-05 21:20

I\'m trying to do something like this:

subs = \'world\'
\"Hello {[subs]}\"

in Python 3.

I can\'t quite figure out the syntax (having co

4条回答
  •  情歌与酒
    2021-02-05 21:59

    The % operator will work, the syntax for which is simple:

    >>> subs = 'world'
    >>> 'Hello %s' % subs
    'Hello world'
    

    The new syntax for string formatting allows for additional options, heres a snippet from the python docs overviewing the basic ways to use the newer str.format() method:

    >>> '{0}, {1}, {2}'.format('a', 'b', 'c')
    'a, b, c'
    >>> '{}, {}, {}'.format('a', 'b', 'c')  # 2.7+ only
    'a, b, c'
    >>> '{2}, {1}, {0}'.format('a', 'b', 'c')
    'c, b, a'
    >>> '{2}, {1}, {0}'.format(*'abc')      # unpacking argument sequence
    'c, b, a'
    >>> '{0}{1}{0}'.format('abra', 'cad')   # arguments' indices can be repeated
    'abracadabra'
    

    So using the newer syntax, a simple resolution to your problem would be:

    >>> subs = 'world'
    >>> 'Hello {}'.format(subs)
    'Hello world'
    

提交回复
热议问题