Formatted output mode one: (%s)
We will often output similar ' Dear XXX Hello! You xx month of the charge is XX, the balance is xx ' such as the string ', and the content of XXX is based on variable changes, so, need a simple way to format the string.
In Python, the% operator is used to format a string. Inside the string,%s is replaced with a string,%d is replaced with an integer, there are several% placeholder, followed by a number of variables or values, the order to correspond well.
If there is only one%, the parentheses can be omitted. When the%s method in Python is passed, it can also be considered a function parameter in the shell.
Name = input ('Please enter your first name:') Age= Input ('Please enter your age:') Job= Input ('Please enter your occupation:') Hobbie= Input ('Please enter your hobby:') msg=" "------------Info of%s-----------Name:%sage:%djob:%shobbie:%s-------------end-----------------" "%(name, name, int (age), job, Hobbie)Print(msg)
Sometimes, what happens if the% inside the string is a normal character? This time you need to escape, with a percent of%
Print (' My name is%s, this year%d, learning progress 2%%' % (' li light ', 10000)
If you're not sure what to use,%s will always work, and it will convert any data type to a string:
Name = input ('Please enter your first name:') Age= Input ('Please enter your age:') Job= Input ('Please enter your occupation:') Hobbie= Input ('Please enter your hobby:') msg=" "------------Info of%s-----------Name:%sage:%sjob:%shobbie:%s-------------end-----------------" "%(name, name, int (age), job, Hobbie)Print(msg)
Mode two: (Format function)
The Format function also implements formatted output by replacing it in three ways:
Usage One :
Similar to the one described above, the difference is that%s is replaced with the ' {} ' brace, which still needs to be in the order of the call.
" my name is {}, this year {}, hobby {} " S1= S.format (' key- footed ' woman '
Usage Two:
Specifies the location of the receive parameter by means of the {n} method, passing in the parameter passed in at the time of the call. The number of parameters can be reduced compared to%s, which enables the reuse of parameters.
" My name is {0}, this year {1}, hobby {2}, I still call {0} " S1= S.format (' key- footed ' woman '
Usage Three:
The name is specified by means of the {str} method, which is invoked using str= ' xxx ' to determine the parameter passed in.
" my name {name}, this year {age}, hobby {hobby} " S1= S.format (age=25,hobby='girl', name=' key foot ')
Python: Formatted output