string formatting of Python

Source: Internet
Author: User

There are two ways to format a string: One, "%" mode, two, format mode;

A, "%" way

1,% Transfer value:%s: can receive any value;

%d: Receive numbers;

1msg ='My name is%s'%'Zhangsan' #STR type2MSG1 ='He is%s'%20#He is type int3MSG2 ='She likes%s'%['Apple','Orange','Pai']#she likes [' Apple ', ' orange ', ' pai ']4 #In the following string formatting, formatting with a tuple data type occurs with the following error: Not all parameters can be converted5 #msg3 = ' She likes%s '% (' apple ', ' orange ', ' pai ') #TypeError: Not all arguments converted during string formatting6MSG4 ='Her information:%s'%{'name':'Shangxia',' Age': 19,'Hobby':'Reading'}7 Print(msg)8 Print(MSG1)9 Print(MSG2)Ten #print (MSG3) One Print(MSG4) ABaobiao ='sales Revenue:%d'%1000.783341505#sales Revenue: $ -Baobiao1 ='sales Revenue:%.9d'%1000.783341505#000001000 -Baobiao2 ='sales Revenue:%7d'%1000.783341505# + the Print(Baobiao) - Print(BAOBIAO1) - Print(BAOBIAO2)

As can be seen from the code above: In fact,%s is not all data types can be received, receive tuple tuple data type will appear error, why this situation, not%s can pass any value?

I've made the following code again:

1MSG3 ='She likes%s,%s,%s'%('Apple','Orange','Pai')#She likes Apple,orange,pai2MSG3 ='She likes%s,%s,%s'%['Apple','Orange','Pai']#typeerror:not enough arguments for format string3 Print(MSG3)

Cause exclusion Method: 1,%s string formatting is passed in as a whole: data type: int str list DICT can be formatted as a whole;

2,%s Why in this case the return error MSG3 = ' She likes%s '% (' apple ', ' orange ', ' pai '), because the need to format one, while Python thinks you pass in 3 parameters, instead will (' Apple ', ' orange ', ' Pai ') as a tuple

2.%s passed in multiple values

1 ' Her name was%s,age%d,she like%s ' ('juliye', +,'zhuyingtai') 2 Print

Note: If multiple values need to be passed in, the number of parameters passed in and received must be the same

1 #when the number of arguments passed is inconsistent with the number of received parameters, an error is2im ='Her name was%s,age%d,she like%s'%('Juliye', 24,'Zhuyingtai','Zhangsan')#typeerror:not all arguments converted during string formatting3im ='Her name was%s,age%d,she like%s%s'%('Juliye', 24,'Zhuyingtai')4 Print(IM)

3, floating point number format:

1 #If no width is specified, the default is reserved to 6-bit2Percent ='the correct rate is:%f percent'%3.1415926#the correct rate is: 3.1415933 #If you need to print a percent sign, you need to use two percent signs4Percent1 ='the correct rate is:%.3f percent'%3.1415926#3.1425 Print(percent)6 Print(PERCENT1)

4. Summary of string formatting

Formatting Summary Reference Blog: Wupeiqi

(1),% formatted writing format:%[(name)][flags][width]. [Precision]typecode

    1. (name) optional, used to select the specified key, which is mainly used for incoming dictionary;
    2. Flags are optional, and the values to choose from are:
      1. + Right-aligned, positive plus, negative before plus minus;
      2. -left-justified; no sign before positive number, plus minus sign before negative number;
      3. Spaces are right-justified, plus a positive number before a negative number plus a minus sign;
      4. 0 Right alignment, no sign before positive number, minus sign before negative, and 0 padding in blank
    3. Width selectable, occupied widths
    4. ". Precision" optional, number of digits retained after the decimal point
    5. TypeCode required, type required, common types are%s,%d,%f
        1. S, gets the return value of the __str__ method of the passed-in object and formats it to the specified location
        2. R, gets the return value of the __repr__ method of the passed-in object and formats it to the specified location
        3. C, Integer: Converts a number to its Unicode corresponding value, 10 binary range is 0 <= i <= 1114111 (py27 only supports 0-255); character: add character to specified position
        4. O, converts an integer to an octal representation and formats it to a specified location
        5. X, converts an integer to a hexadecimal representation and formats it to a specified location
        6. D, converts an integer, floating-point number to a decimal representation, and formats it to a specified position
        7. E, converting integers, floating-point numbers to scientific notation, and formatting them to a specified location (lowercase e)
        8. E, converting integers, floating-point numbers into scientific notation, and formatting them to a specified position (uppercase E)
        9. F, converts an integer, floating-point number to a floating-point number representation, and formats it to a specified position (the default is 6 digits after the decimal point)
        10. F, ibid.
        11. G, auto-adjust convert integers, floating-point numbers to floating-point or scientific notation (more than 6 digits in scientific notation), and format them to a specified location (if scientific counts are e;)
        12. G, auto-adjust convert integers, floating-point numbers to floating-point or scientific notation (more than 6 digits in scientific notation), and format them to a specified location (if scientific counts are e;)
        13. %, when there is a format flag in the string, a percent sign is required

(2), common formatting

1 #passing in a single value2TPL ="I am%s"%"Alex"3 #Pass in multiple values4 #TPL = "I am%s age%d"% ("Alex") #i is Alex age5 #use a dictionary to specify a key value for the value to be passed6 #TPL = "I am%" (name) s age% (age) d "% {" name ":" Alex "," Age ":7 #incoming floating-point type, reserved to decimal 2 bits8 ## TPL = "percent%.2f"% 99.976239 ##传入浮点型, use a dictionary to specify the key value for incomingTen ## TPL = "I am% (PP)." 2f "% {" pp ": 123.425556,} One ##如果使用字典进行传值的时候, you must specify the key value, or you will get an error. ATPL ="I am%.2f percent"% {"pp": 123.425556,}#Typeerror:must is real number, not dict - Print(TPL)

Ii. format formatting

1. Format formatted writing format

[[Fill]align] [Sign] [#] [0] [Width] [,] [. Precision] [Type]

  1. Fill "optional" white space filled with characters
  2. Align "optional" alignment (required with width)
  3. <, content left justified
  4. Content right-aligned (default)
  5. =, the content is right-aligned, the symbol is placed to the left of the padding character, and only valid for numeric types. Even: symbol + filler + number
  6. ^, content centered
  7. Sign "optional" with unsigned numbers
  8. +, positive home Plus, minus plus negative;
  9. -The plus sign does not change, minus is negative;
  10. Spaces, plus spaces, minus signs and negative;
  11. "Optional" for binary, octal, hex, if plus #, 0b/0o/0x is displayed, otherwise not displayed
  12. , "optional" adds a delimiter to the number, such as: 1,000,000
  13. width "Optional" format the size of the placeholder
  14. . Precision "optional" decimal digits reserved Precision
  15. Type "optional" formatting types
  16. Parameters passed into the string type
  17. s, format string type data
  18. Blank, no type specified, default is None, same as S
  19. Parameters passed into the integer type
  20. B, automatic conversion of 10 binary integers to 2 binary representation and then formatting
  21. C, automatic conversion of 10 binary integers to their corresponding Unicode characters
  22. d, decimal integer
  23. O, the 10 binary integers are automatically converted to 8 binary representation and then formatted;
  24. X, automatically converts 10 binary integers to 16 binary representation and then formats (lowercase x)
  25. X, automatically converts 10 binary integers to 16 binary representation and then formats (uppercase X)
  26. Parameters passed in floating-point or decimal type
  27. E, converted to scientific notation (lowercase e), and then formatted;
  28. E, converted to scientific notation (capital E), and then formatted;
  29. F, converted to floating-point type (6 digits after the default decimal point), and then formatted;
  30. F, converted to floating-point type (6 digits after the default decimal point), and then formatted;
  31. G, automatically switch between E and F
  32. G, automatically switch between E and F
  33. %, display percent (default = 6 digits after decimal point)

2. Formatting common format

1 #I am seven, age, Alex2 #TPL = "I am {}, age {}, {}". Format ("Seven", ' Alex ')3 #I am seven, age, Alex4 #TPL = "I am {}, age {}, {}". Format (*["Seven", "Alex")5 #I am seven, age, really seven6 #TPL = "I am {0}, age {1}, really {0}". Format ("seven", +)7 #I am seven, age, really seven8 #TPL = "I am {0}, age {1}, really {0}". Format (*["seven", +])9 #I am seven, age, really sevenTen #TPL = "I am {name}, age {age}, really {name}". Format (name= "Seven", age=18) One #I am seven, age, really seven A #TPL = "I am {name}, age {age}, really {name}". Format (**{"name": "Seven", "Age":) - #I am 1, age 2, really 3 - #TPL = "I am {0[0]}, age {0[1]}, really {0[2]}". Format ([1, 2, 3], [One, one, one]) the #I am seven, age, Money 88888.100000 - #TPL = "I am {: s}, age {:d}, Money {: F}". Format ("Seven", 88888.1) - #I am seven, age -TPL ="I am {: s}, age {:d}". Format (*["Seven", 18]) + # - #TPL = "I am {name:s}, age {age:d}". Format (name= "Seven", age=18) + # A #TPL = "I am {name:s}, age {age:d}". Format (**{"name": "Seven", "Age":) at # - #TPL = "Numbers: {: b},{:o},{:d},{:x},{:x}, {:%}". Format (2 , A, a, a, a, a, a, a, a, A/15.87623) - # - #TPL = "Numbers: {: b},{:o},{:d},{:x},{:x}, {:%}". Format (2 , A, a, a, a, a, a, a, a, A/15.87623) - # - #TPL = "numbers: {0:b},{0:o},{0:d},{0:x},{0:x}, {0:%}". Format ( in # - #TPL = "numbers: {num:b},{num:o},{num:d},{num:x},{num:x}, {num:%}". Format (num=15) to Print(TPL)

3.

string formatting of Python

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.