Python format function, python string format
1. The format can accept infinite parameters, and the positions can be unordered:
In [1]: "{}{}". format ("hello", "world") # do not set the location, In the default order Out [1]: 'Hello World' In [2]: "{0} {1 }". format ("hello", "world") # specify the location Out [2]: 'Hello World' In [3]: "{1} {0} {1 }". format ("hello", "world") # specify the location and reuse the parameter Out [3]: 'World hello World' In [4]: "{name} {age }". format (name = "Linda", age = 15) # Use the keyword Out [4]: 'linda 15' # Set the parameter In [5] through the dictionary: info = {"name": "Linda", "age": 15} In [6]: "{name} {age }". format (** info) Out [6]: 'linda 15' # Set the parameter In [7]: my_list = ['hello' through the list ', 'World'] In [8]: "{0 [0]} {0 [1]}". format (my_list) Out [8]: 'Hello world'
2. format control: the syntax is {} with a colon (:)
^, <,> Indicates the center, left, and right alignment, respectively, with width and padding after the sign. Only one character can be entered. If this parameter is not specified, spaces are used by default.
+ Indicates that + is displayed before a positive number, and-is displayed before a negative number. (Space) indicates that a space is added before a positive number.
B, d, o, and x are binary, decimal, octal, and hexadecimal respectively.
# Center display. The length is 4In [9]: "{: ^ 4 }". format ("he") Out [9]: 'hes' # Left alignment, Length: 4, blank space filled with "x" In [10]: "{: x <4 }". format ("he") Out [10]: 'hexx' # displays the positive and negative signs In [11]: "{:+ }". format (-3) Out [11]: '-3' # the binary value of 8 is displayed In [12]: "{: B }". format (8) Out [12]: '000000' # use braces {} to escape braces In [13]: "{} is {0 }}". format ("hello") Out [13]: 'Hello is {0 }'