Basis of the String Format
The string format is a technique that
can be used to insert a specific value into the string that you want to print
out. The type of value inserted is determined by a string format code. The
string format is used in the following manner.
print(“output string1 %s output string2” % inserted string) |
Insert
the string format code in the middle of the output string. Place the characters
that you want to insert with the “%” code after the string.
String Format Code
%s |
String |
%c |
Character |
%d |
Integer |
%f |
Floating
Pointer |
%o |
Octal
Number |
%x |
Hexadecimal
Number |
String Formatting
Let's
learn how to use the string format through a simple example.
print("print string: [%s]" % "test") print("print string: [%10s]" % "test") #(1) print("print character: [%c]" % "t") print("print character: [%5c]" % "t") #(2) print("print Integer: [%d]" % 17) print("print Float: [%f]" % 17) #(3) print("print Octal: [%o]" % 17) #(4) print("print Hexadecimal: [%x]" % 17) #(5) >>> print string: [test] print string: [ test] print character: [t] print character: [ t] print Integer: [17] print Float: [17.000000] print Octal: [21] print Hexadecimal: [11] |
Format
String
If you use the string formatting codes and the numbers
together, the characters can be used to secure a space according to the size of
the numbers that are printed on the screen.
(1) Printing a Fixed Length Character
String: If “%s” is used with a
number, it secures space by an amount corresponding to the number. In the
example, “test” is printed using 4 digits, and spaces are printed for the
remaining six digits, so all 10 characters are printed.
(2) Printing a Fixed Character Containing
Spaces of a Certaiin Length: If “%c” is used with a
number, the amount corresponding to the number that is same a “%s” is printed. Therefore,
one character and four blanks are printed.
(3) The string is the same as that used with the number "%
c", which can be output only as a long number. The character of you,
4-digit blank is output
(3) Real
Number: “17” is converted into a real number.
(4) Octal: “17” is converted into an octal number, and “21” is printed.
(5) Hex: “17” is converted into a hex number, and “11” is printed.