Python Chapter III-String __python

Source: Internet
Author: User
Chapter III Strings

3.1 Basic String Operations

Python's strings and tuples are about the same and cannot be changed, and if you want to change the value, you can try to modify it after the list serialization.
{
Website = ' http://www.Python.org ';
Website = [-3:] = ' com ';
It is illegal to operate above.
}

3.2 String Format: Compact version
String formatting is implemented using the string format operator (the name is still appropriate), or%.
Basic usage examples
1.
>>> format = "Hello,%s.%s enough for ya?";
>>> values = (' World ', ' hot ');
>>> print (format% values);
Hello, world. Hot enough for ya?
2.
>>> format = "Pi with three decimals:%.3f";
>>> from Math import pi
>>> print (format% pi)
Pi with three decimals:3.142
3. Template string
< basic usage >
>>> from string import Template;
>>> s = Template (' $x. Glorious $x! ');
>>> S.substitute (x= ' Slurm ')
' Slurm. Glorious slurm! '

< template string If you are with another word, then {x} distinguishes >
>>> s = Template ("It ' s ${x}tastic!")
>>> S.substitute (x= ' Slurm ')
"It ' s slurmtastic!"
>>>
< display dollar characters with two $>
>>> s=template ("Make $$ selling $x!");
>>> S.substitute (x= ' Slurm ')
' Make $ selling slurm! '

< In addition to keyword parameters, you can also use dictionary variables to provide value/name pairs >
>>> s = Template (' A $thing must never $action. ');
>>> d = {}
>>> d[' thing '] = ' gentleman '
>>> d[' action '] = ' show his socks '
>>> S.substitute (d)
' A gentleman must never show his socks. '

<safe_substitute does not complain when the search is not found >
>>> s = Template (' A $x ');
>>> S.substitute (a= ' x ') this will be an error, because you cannot find
>>> S.safe_substitute (a= ' x ') will not error, and output the nominal value
' A $x '

3.3 String Formatting: Full version
The right-hand operand of the format operator can be anything, and if it is a tuple or a mapping type (such as a dictionary), the string format will vary.

Attention:
If a transformation expression is part of a tuple, you must enclose it in parentheses to avoid an error.
{
Ok
>>> '%s plus%s equals%s '% (1, 1, 2)
' 1 plus 1 equals 2 '
Error
>>> '%s plus%s equals%s '% 1,1,2
Traceback (most recent call last):
File "<pyshell#27>", line 1, in <module> '%s ' plus%s equals%s '% 1,1,2
Typeerror:not enough arguments for format string
>>>
}

Basic conversion specifier-(the following describes the importance of sequential (in order of use))
(1% character: The start of the token conversion specifier.
(2) conversion sign (optional):-to indicate left alignment;
                 + indicates that you want to add a positive sign before converting the value
Leave space Before "" positive number
                  0 0 Padding
(3 Minimum field width (optional): The converted string should have at least the width of the specified value.
If it is *, the width is read from the value tuple.

(4) after the point (.) followed by the precision value (optional): If the conversion is real, the precision value indicates the number of digits after the decimal point. If you convert a string, the number represents the maximum field width. If it is *, then the precision will be read from the tuple.

(5) Conversion type
D,i signed Decimal integer
o Octal with no sign
U without symbol decimal
X,x Hex
E,e Scientific Counting method
F,f Decimal Floating-point type
G,g
C-word character
R string (convert any Python object using repr)
s string (convert any Ptthon object using str)


3.3.1 Simple Conversion
>>> ' eggs: $%d '%42
' Price of eggs: $42 '
>>> ' eggs: $%d '%42
' Price of eggs: $42 '
>>> ' hexadecimal price of eggs:%x '%42
' Hexadecimal price of eggs:2a '
>>> from Math import pi
>>> ' Pi:%f ... '%pi
' pi:3.141593 ... '
>>> ' Very inexact estimate of pi:%i '%pi
' Very inexact estimate of Pi:3 '
>>> ' Using str:%s '% 42L
Syntaxerror:invalid syntax (I bought in the 3.5 high version did not show L)
>>> ' Using str:%s '% 42
' Using str:42 '
>>> ' Using repr:%r '%42
' Using repr:42 '
>>>

3.3.2 Field width and precision

>>> '%10f '%pi '

3.141593 ' >>> '%10.2f '%pi
' 3.14 '
>>> '%.2f '%pi
' 3.14 '
>>> '%.2s '%pi
' 3. '
>>> '%.5s '% ' Guido van Rossum '
' Guido '
< length can be replaced with *, and then given in the tuple >
>>> '%.*s '% (5, ' Guido van Rossum ')
' Guido '

3.3.3 symbols, alignment, and 0 padding
<0 Filling >
>>> '%010.2f '%pi
' 0000003.14 '
< left alignment >
>>> '%-10.2f '%pi
' 3.14 '
< space fill >
>>> print ('% 5d '%10) + ' \ n ' + ('% 5d '%-10)]
10
-10

< sign >
>>> print ('%+5d '%10) + ' \ n ' + ('%+5d '%-10)]
+10
-10
3.4 String method
String constants
{
    String.digits 0~9
    String.letters All letter Case
    String.lowercase All lowercase Letters
    String.printable A string of characters that are printed in all classes
    String.punctuation A string containing all punctuation
    String.uppercase a string of all uppercase letters
}
    String constants, such as string.letters, differ from regions in that they depend on the language that Python configures, and if you can be sure that you are using ASCII then you can do this for example string.ascii_letters

3.4.1 Find (finds output leftmost, no output found-1)
>>> mark = "123456789123456789"
>>> mark.find ("123456")
0
>>> mark.find ("AASD")
-1

acceptable interval definition [)
{
>>> subject = "$$$ Get rich now!!! $$$"
>>> subject.find ("$$$")
0
>>> subject.find ("$$$", 1)
20
>>> subject.find ("!!!", 0, 16)
-1
}


3.4.2 Join a very important string method, which is the inverse method of the split method, used to add elements to the queue
{
>>> seq = [1,2,3,4,5]
>>> Sep = ' + '
>>> sep.join (seq)
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
Sep.join (seq)
Typeerror:sequence Item 0:expected STR instance, int found

>>> seq = [' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ']
>>> sep.join (seq)
' 1+2+3+4+5 '

>>> Sep
'+'

>>> seq
[' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ']

>>> dirs = ', ' usr ', ' bin ', ' env '
>>> '/'. Join (dirs)
'/usr/bin/env '

>>> print (' C: ' + ' + '. Join (dirs))
C:\usr\bin\env
>>>
}

3.4.3 Lower (title all initials, other lowercase)
Lower method returns the lowercase master of a string
{
>>> ' Asdaaddasdwdsdw '. Lower ()
' Asdaaddasdwdsdw '
>>> name = ' Gumby '
>>> names = [' Gumby ', ' Smith ', ' Jones ']
>>> if Name.lower () in Names:print (' fount it! ')
Fount it!
>>>
}
3.4.4 Replace replacement
{
>>> "This is a test". Replace (' is ', ' EEZ ')
' Theez eez a test '
}

3.4.5 Split (a jion inverse method used to segment a string into a sequence).
{
>>> ' 1+2+3+4+5+6 '. Split (' + ')
[' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ']

>>> '/use/dasd/w/ad/we '. Split ('/')
[', ' use ', ' DASD ', ' W ', ' ad ', ' we ']

< If you do not provide a delimiter, all spaces will be used as delimiters >
>>> "Using the Default". Split ()
[' Using ', ' the ', ' Default ']
}
3.4.6 strip removes spaces on either side of the string (you can also specify the removal character)
{
>>> ' ASDASD '. Strip ()
' ASDASD '

>>> ' 000asd000asd00012 '. Strip (' 012 ')
' ASD000ASD '
}
3.4.7 Translate this 3.5 has been canceled, this is not read first.


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.