String substitution in Python 3?

I am trying to do something like this:

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

in Python 3.

I can not understand the syntax (coming from Ruby / PHP). Am I missing something? The% operator in documents that, it seems to me, does not support Python 2.x.

+8
source share
4 answers

You have two formatting options:

  • Old %python2 style statement that works with C-printf-style format strings
  • New format()python3 style method for string. Due to backport, you can use this option in both python2 and python3.
  • Even newer Python 3. 6+ lines that are not wrapped in python2: they allow you to specify expressions inside string literals

% C-printf-style:

"Hello %s" % subs
"Hello %s%s" % (subs, '.')
my_dict = {'placeholder_name': 'world', 'period': '.'}
"Hello %(placeholder_name)s%(period)s" % my_dict

, python %s ( , ..) str() . %r repr() . , %f, , (, ) (, %.5f).

format():

"Hello {}".format(subs)
"Hello {placeholder_name}".format(placeholder_name=subs)

, placeholder_name subs, , . , :

"Hello {subs}".format(subs=subs)

python , , :

my_tuple = ('world', '.')
"Hello {}{}".format(*my_tuple)
my_dict = {'subs': 'world', 'period': '.'}
"Hello {subs}{period}".format(**my_dict)

, , format().

, ( args of format()) , , . , .

3. 6+ f-:

>>> x=5
>>> y=6
>>> f'woof {x*y} meow'
'woof 30 meow'
+13

, Python .

Python 3.6 . :

PEP 0498 -

>>> name = 'Fred' 
>>> f'He said his name is {name!r}.'  
"He said his name is 'Fred'."
+9

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

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

The new string formatting syntax allows you to use additional parameters; it is a fragment from python documents that discusses the main ways to use the new 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'

Thus, using the new syntax, a simple solution to your problem would be:

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

You can use both% and format - not some of them are outdated

subs = 'world'

print ("hello %s" % subs)
print ("hello {}".format(subs))
print ("hello {subs}".format(**locals()))

Enjoy

0
source

All Articles