The third chapter using Python string (1) Lite

All standard sequence of operations (index, sliced, multiplication, membership check, length, minimum, maximum) are suitable string.

However, the string can not be made, so that all the elements have to slice assignments and assignments are illegal.

1.% s format the string conversion specifier

% Left specifies a string to specify the right settings to format (single value may be used [e.g. string or numeric], using the tuple [worth a plurality of formats], may also be used dictionaries)

1 formats = "Hello, %s! %s enough for you?"
2 value = ('world', 'Hot')
3 final_format = formats % value
4 print(final_format)
5 结果:
6 Hello, world! Hot enough for you?

2. template string (similar to the UNIX shell syntax too)

In the format string was set, the key parameters can be viewed as a way to provide a worthy replacement named field.

The following parameters contain an equal sign is called keyword arguments

1 from string import Template
2 tmpl = Template("Hello, $who! $what enough for you?")
3 tmpl_final = tmpl.substitute(who="Mars", what="Dusty")
4 print(tmpl_final)
5 结果:
6 Hello, Mars! Dusty enough for you?

3. String method format (encoding a new era, recommended !!!)

Each replacement fields are enclosed with braces, which may include name, may also contain information about how the corresponding values ​​for conversion and formatting.

 1 str = "{}, {} and {}".format("first", "second", "third")
 2 print(str)
 3 结果:first, second and third
 4 
 5 str1 = "{0}, {1} and {2}".format("first", "second", "third")
 6 print(str1)
 7 结果:first, second and third
 8 
 9 str2 = "{3} {0} {2} {1} {3} {0}".format("be","not","or","to")
10 print(str2)
11 结果:to be or not to be
Keyword parameters does not matter the order; 
to specify the format specifier .2f, colon and separate it from the field name.
. 1  from Math Import PI, E 
in the order of # irrelevant keyword parameter. It specifies the format specifier .2f, with a colon and the field name spaced
2 STR = " {name} {IS Approximately value: .2f}! " .Format (= PI value, name = " [pi] " ) . 3 Print (str) results: pi IS Approximately 3.14 !
Alternatively, if the variable field of the same name, abbreviated following manner: the string preceded f.
. 1  from Math Import PI, E
 2  
. 3  # If the variable substitution field with the same name, abbreviated following manner: the string preceded F 
. 4 str1 = F " the Euler apos Constant IS Roughly {E}! " 
. 5  Print (str1)
 . 6  
. 7  # equivalent expression 
. 8 str2 = " the Euler apos Constant IS Roughly {E}! " .format (E = E)
 . 9  Print (str2)
 10  
. 11  results:
 12 is the Euler ' S Constant IS Roughly 2.718281828459045! 
13 is the Euler ' S Constant IS Roughly 2.718281828459045!

3.3 Set string format: Full - subsequent re-learning / P43

 

Guess you like

Origin www.cnblogs.com/ElonJiang/p/11318936.html