Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

str.format() option is not working

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?

like image 745
Netherwire Avatar asked Dec 05 '13 09:12

Netherwire


People also ask

What is str format () in Python?

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.

How do you use %s in Python?

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.

What is %d %s in Python?

%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.


1 Answers

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!
like image 179
Inbar Rose Avatar answered Sep 24 '22 22:09

Inbar Rose