Format the python string and format the python string.
Most of the time, when printing input content, we want a simple format instead of splicing.
General Practice:
1 name = input("name:").strip()2 age = input("age:").strip()3 job = input("job:").strip()4 print("Name:" + name + " Age:" + age + " Job:" + job)
Result:
Name:zhang Age:24 Job:IT
Format the output:
Name = input ("name :"). strip () age = input ("age :"). strip () job = input ("job :"). strip () info = ''' ---------- info of % s ------- # Every % s in info is a placeholder Name: % sAge: % sJog: % s ---------- end --------------- ''' % (name, name, age, job) # % of this line is to associate the placeholder with the variable following the brackets with print (info)
Result:
----------info of zhang -------Name : zhangAge : 24Jog : IT----------end---------------
In addition to % s, there are % d. % d indicates that you can only enter numbers. We will change % s of age to % d to see what will happen.
1 name = input("name:").strip() 2 age = input("age:").strip() 3 job = input("job:").strip() 4 info = ''' 5 ----------info of %s ------- 6 Name : %s 7 Age : %d 8 Jog : %s 9 ----------end---------------10 '''%(name, name, age, job)11 print(info)
Error message:
Traceback (most recent call last): File "C:/Users/admin/PycharmProjects/test.py", line 10, in <module> '''%(name, name, age, job)TypeError: %d format: a number is required, not strName:li Age:25 Job:farmer
The reason is that the input is a number but saved to the variable as a string 'str' type. To use % d, you must modify the variable type, you can change the age variable of row 10th to the int type as follows to run the command normally.
'''%(name, name, int(age), job)
Therefore, in formatting output, % s is more omnipotent, Because you input a string 'str', so no error is reported.