TypeError: not enough arguments for format string when using %s

前端 未结 2 1378
孤城傲影
孤城傲影 2021-01-02 07:32

this is my code

import sys
name = input(\"Enter your name:\")
last_name = input(\"Enter your last name:\")
gender = input(\"Enter your gender:\")
age = input         


        
相关标签:
2条回答
  • 2021-01-02 08:17

    You need to put your arguments for string formatting in parenthesis:

    print (... % (name, last_name, gender, age))
    

    Otherwise, Python will only see name as an argument for string formatting and the rest as arguments for the print function.


    Note however that using % for string formatting operations is frowned upon these days. The modern approach is to use str.format:

    print ("So your name is {}, your last name is {}, you are {} and you are {} years old".format(name, last_name, gender, age))
    
    0 讨论(0)
  • 2021-01-02 08:30

    You need a set of parenthesis:

    >>> '%s %s' % 'a', 'b'  # what you have
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: not enough arguments for format string
    >>>
    >>>
    >>> '%s %s' % ('a', 'b')  # correct solution
    'a b'
    

    '%s %s' % 'a', 'b' is evaluated as ('%s %s' % 'a'), 'b', which produces an error in '%s %s' % 'a' since you have fewer arguments than format specifiers.


    print("So your name is %s, your last name is %s, you are %s and you are %s years old" % (name, last_name, gender, age))
    
    0 讨论(0)
提交回复
热议问题