This code was taken from the tutorial:
def main():
stri = "Hello, {person}"
stri.format(person="James")
print(stri) #prints "Hello, {person}"
Why the format()
is not working?
Python's str. format() method of the string class allows you to do variable substitutions and value formatting. This lets you concatenate elements together within a string through positional formatting.
The %s operator is put where the string is to be specified. The number of values you want to append to a string should be equivalent to the number specified in parentheses after the % operator at the end of the string value.
%s is used as a placeholder for string values you want to inject into a formatted string. %d is used as a placeholder for numeric or decimal values. For example (for python 3) print ('%s is %d years old' % ('Joe', 42)) Would output Joe is 42 years old.
It does work. You were just not assigning the format to a variable, and then just printing the original string. See example below:
>>> s = 'hello, {person}'
>>> s
'hello, {person}'
>>> s.format(person='james')
'hello, james' # your format works
>>> print s # but you did not assign it
hello, {person} # original `s`
>>> x = s.format(person='james') # now assign it
>>> print x
hello, james # works!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With