Advanced Usage python3 f-string format string

  Starting Python 3.6, f-string is a string formatted great new method. Compared with other formatting way, they are not only easier to read, more concise and less error-prone, and faster!

Before Python 3.6, two embedded into the Python expression text string for formatting the main method: %-formattingand str.format().

%-formatting

% String object with the use of built-operator operation, you can use it to format string.

= name "tom" 
Print ( "cat's name is% s"% name)

 Output:

cat name is tom

The above example code looks readable enough, however, once we started the string parameters and a longer code will become less easy to read.

name = "tom"
age = 2
action = "quickly"
disposition = "懒"

print ( "cat's name is% s,% d years old this year, and mouse very% s, but very% s, total sleep during the day."% (name, age, action, disposition))

Output:

Cat's name is tom, 2 years old today, and mouse very quickly, but very lazy, total sleep during the day.

str.format()

str.format()It is %-formattingimproved. It uses the normal function call syntax, and may be converted to an object by a character string __format __()expanding method.

Use str.format()replacement fields marked with braces:

= name " tom " 
Print ( " cat's name} { " .format (name))

Output:

Tom cat's name

It may be by reference in its index, reference variables in any order:

name = "tom"
age = 2

Print ( " cat's name is {1}, {0} years old this year, and today a week {0} " .format (Age, name))

Output:

Cat's name is tom, 2 years old, and today Week 2

 

Guess you like

Origin www.cnblogs.com/testlearn/p/11704984.html