Python formatted string
In the process of writing a program, it is often necessary to format the output, each time with a check. Just sort it out here for indexing.
Format operator (%)
"%" is a Python-style string formatting operator, very similar to the C language of the printf () function of the string formatting (C language is also used in%).
Here's a look at the string formatting in Python conforms to:
Formatting symbols |
Description |
%c |
Convert to character (ASCII value, or string of one length) |
%r |
Prioritize string conversions with the repr () function |
%s |
Prioritize string conversions with the STR () function |
%d/%i |
Turn into a signed decimal number |
%u |
Turn into unsigned decimal numbers |
%o |
Turn unsigned octal number |
%x/%x |
Turns to unsigned hexadecimal number (x/x represents the case of the converted hexadecimal character) |
%e/%e |
Turn into scientific notation (e/e control output e/e) |
%f/%f |
Convert to floating point (fractional part naturally truncated) |
%g/%g |
Shorthand for%e and%f/%e and%f |
%% |
Output% (the formatted string includes a percent semicolon, so you must use a percentile) |
The formatting that is listed here is fairly simple, and the only thing you want to emphasize is the difference between "%s" and "%r".
To see a simple code:
string = "hello\twill\n" print "%s"%stringprint "%r"%string
The output of the code is:
In fact, the difference here is the difference between the two built-in functions of STR () and repr ():
- STR () The resulting string is user-oriented and has good readability
- Repr () The resulting string is machine-oriented
- Typically (not all) repr () results are: obj = = eval (repr (obj))
Formatting operator Helper
String formatting is possible with "%", but "%" is often used in conjunction with the following helper characters.
Auxiliary symbols |
Description |
* |
Define width or decimal precision |
- |
Used for left justification |
+ |
Show plus sign (+) in front of positive number |
# |
Display 0 (0) in front of octal numbers, "0x" or "0X" before hexadecimal (depending on "x" or "X") |
0 |
The displayed number is preceded by "0" instead of the default space |
(VAR) |
Mapping variables (typically used to process parameters of a field type) |
M.n |
M is the minimum total width displayed, and n is the number of digits after the decimal point (if available) |
Take a look at some simple examples:
num = 100print "%d to hex are%x"% (num, num) print "%d to hex are%x"% (num, num) print "%d to hex is% #x"% (num, num) print " %d to hex is% #X "% (num, num) # floating-point number F = 3.1415926print" value of F is:%.4f "%f# Specify width and alignment students = [{" Name ":" Wilber "," age " : +}, {"name": "would", "Age":-}, {"Name": "June", "Age": 27}]print "Name:%10s, Age:%10d"% (students[0]["name"], students [0] ["Age"]) Print "Name:%-10s, Age:%-10d"% (students[1]["name"], students[1]["age"]) print "Name:%*s, Age:%0*d"% (students[2][" Name "], students[2][" Age "]) # Dict parameter for student in Students:print '% (name) s is% (age) D years old"%student
The code output is:
For Python's format operators, you can not only accept the parameters of the tuple type, but also support dict, like the last part of the code above, then you can use "% (key) S" directly in the format string. (s) represents the corresponding value in Dict, depending on the type of change.
String templates
In fact, formatting strings in Python, in addition to formatting operators, can also use String template objects in the string module. Here's a look at the substitute () method of the Template object:
From string Import Templates = Template ("Hi, $name! $name is learning $language ") Print S.substitute (name=" Wilber ", language=" Python ") d = {" name ":" would "," language ":" C # "} Print S.substitute (d) # uses $$ to represent $ sign s = Template ("This book ($bname) is 17$$") Print S.substitute (bname= "TCP/IP")
The code results are:
String built-in function format ()
Python2.6 begins with the addition of a function str.format () that formats the string, which can also be formatted with the string. In the format () function, use the "{}" symbol as the format operator.
The basic use of the format () function is demonstrated directly below through some simple examples:
# positional parameter print "{0} is {1} years old". Format ("Wilber", "page") print "{} is {} years old". Format ("Wilber", "page") print "Hi, {0}! {0} is {1} years old ". Format (" Wilber ", 28) # keyword parameter print" {name} is {age} years old ". Format (name =" Wilber ", age = 28) # Subscript parameter Li = ["Wilber", 28]print "{0[0]} is {0[1]} years old". Format (LI) # fill and align # ^, <, > are centered, left-aligned, right-aligned, followed by the width #: character followed by a fill, which can only be a Characters, not specified by default, are populated with blanks with the print ' {: >8} '. Format (' 3.14 ') print ' {: <8} '. Format (' 3.14 ') print ' {: ^8} '. Format (' 3.14 ') print ' { : 0>8} '. Format (' 3.14 ') print ' {: a>8} '. Format (' 3.14 ') # floating-point precision print ' {:. 4f} '. Format (3.1415926) print ' {: 0>10.4f } '. Format (3.1415926) # binary # B, D, O, X are binary, decimal, octal, hexadecimal print ' {: b} '. Format (one) print ' {:d} '. Format (one) print ' {: o} '. Format (one) print ' {: x} '. Format (one) print ' {: #x} '. Format (one) print ' {: #X} '. Format (11) # Thousands separator print ' {:,} '. Format ( 15700000000)
The built-in function of STR
At the very beginning, Python had a dedicated string module, which was to import the module before using the string method. Starting with Python2.0, for ease of use, the STR type adds a number of built-in functions that implement the same functions as functions in the string module, that is, if S is a string object, you can use the built-in function directly instead of the import.
For formatting strings, you might also consider using the other built-in functions of STR:
>>> dir (str) [' __add__ ', ' __class__ ', ' __contains__ ', ' __delattr__ ', ' __doc__ ', ' __eq__ ', ' __format__ ', ' __ge_ _ ', ' __getattribute__ ', ' __getitem__ ', ' __getnewargs__ ', ' __getslice__ ', ' __gt__ ', ' __hash__ ', ' __init__ ', ' __le__ ', ' _ _len__ ', ' __lt__ ', ' __mod__ ', ' __mul__ ', ' __ne__ ', ' __new__ ', ' __reduce__ ', ' __reduce_ex__ ', ' __repr__ ', ' __rmod__ ', ' __ Rmul__ ', ' __setattr__ ', ' __sizeof__ ', ' __str__ ', ' __subclasshook__ ', ' _formatter_field_name_split ', ' _formatter_ ' Parser ', ' capitalize ', ' center ', ' count ', ' decode ', ' encode ', ' endswith ', ' expandtabs ', ' find ', ' format ', ' Index ', ' Isaln Um ', ' isalpha ', ' isdigit ', ' islower ', ' isspace ', ' istitle ', ' isupper ', ' join ', ' ljust ', ' lower ', ' lstrip ', ' partition ', ' r Eplace ', ' rfind ', ' rindex ', ' rjust ', ' rpartition ', ' rsplit ', ' Rstrip ', ' Split ', ' splitlines ', ' startswith ', ' strip ', ' swa ' Pcase ', ' title ', ' Translate ', ' upper ', ' Zfill ']
Here are some of the commonly used STR types built-in functions:
# lowercase s.lower () # Uppercase S.upper () #大小写互换 s.swapcase () # First uppercase s.capitalize () # Output width characters, S left-aligned, insufficient portions are filled with Fillchar, default is a space. S.ljust (Width,[fillchar]) # Right Align S.rjust (Width,[fillchar]) # middle Alignment s.center (width, [Fillchar]) # Returns the label of the first letter of Substr appearing in S, Returns 1 if no substr is in S. The start and end functions are equivalent to searching in s[start:end] for S.find (substr, [Start, [end]]) # Returns the label of the first letter of the last occurrence of substr in S, and returns 1 if there is no substr in S That is to say, the first occurrence of substr from the right is the first letter of the S.rfind (substr, [Start, [end]]) # calculates the number of times substr appears in S s.count (substr, [Start, [end]]) # Replace the Oldstar in S with the Newstr,count as the number of replacements S.replace (Oldstr, Newstr, [Count]) # to remove all the characters in the front and back chars of S, which can be understood as replacing s and chars with none S.strip ([chars]) S.lstrip ([chars]) S.rstrip ([chars]) # divides S into a list with Sep as a delimiter. Maxsplit represents the number of splits. The default delimiter is a white-space character s.split ([Sep, [Maxsplit]]) # string sequence represented by SEQ, connected with S s.join (seq)
Summarize
This article has compiled some formatting characters, as well as some auxiliary instructions, in combination with the format operator (%), you can generate a string in a specific format. You can also use string templates for string formatting.
Python format string ~ Go