Python Basics Tutorial String

Source: Internet
Author: User
    • 1 basic string Operation
    • 2 string formatting: Compact version
      • Font color= "#000000" >2.1 with string format operator
      • 2.2 format string template with string
    • 3 string format: Full version
      • 3.1 conversion specifier
      • 3.2 simple conversion
      • 3.3 field width and precision
      • 3.4 symbol, align and 0 fill
    • 4 string method
      • 4.1 find
      • 4.2 join
      • 4.3 lower
      • 4.4 Replace
      • 4.5 split
      • 4.6 strip
      • 4.7 translate

1 Basic string Operations

  1. Description: String is also a sequence of one, so fragmentation, multiplication, index, length, maximum, minimum, judge membership can be applied to the string;
  2. Note: The string is immutable, so it cannot be assigned a value;
  3. Example
          
         
    The code is as follows Copy Code
    1:   >>> mystr="Test string"
    
    2:  ' t '
    
    3:  traceback (most Recent call Last:
    
    4:  "<pyshell#1>" in <module>
    
    5 :    ' t '
    
    6:  typeerror' str 'object   not support item assignment
    
    7:  >>>
    2String Formatting: Compact version

2.1 operator with string formatting

  1. Description: String formatting using the string format operator percent ( % ) implementation, on the left-hand side of the operator is formatted string, the right is the value you want to be formatted;
  2. Attention:
    1. Only tuples and dictionaries can be formatted into more than one value, and lists and other sequences are formatted as a value;
    2. A conversion specifier that marks where the conversion value needs to be inserted;
    3. If you want to output a percent semicolon in a formatted string, you need to use the %
  3. Example:
           
          
    The code is as follows Copy Code
    1:#一般格式化
    
    2:&gt;&gt;&gt; MyFormat ="Hello, my name is%s%s"
    
    3:&gt;&gt;&gt; name = (' Bill ',' Gunn ')4:&gt;&gt;&gt;Print(MyFormat% name)5:Hello, my Name isBill Gunn6:&gt;&gt;&gt;7:
    
    8:#用列表格式化
    
    9:&gt;&gt;&gt; MyFormat =' Hello, my name is%s '
    
    Ten:&gt;&gt;&gt; name=[' Bill ',' Gunn ']One :&gt;&gt;&gt;Print(MyFormat% name)A :Hello, my Name is[' Bill ',' Gunn ']:
    
    :#打印浮点数
    
    :&gt;&gt;&gt;ImportMath:&gt;&gt;&gt;Print("PI =%.5f"% pi):PI= 3.14159:
    
    :#打印百分号
    
    :&gt;&gt;&gt;Print("%.2f%%"% 22.3):22.3%:&gt;&gt;&gt;
    2.2Format strings with template of string
  1. Description: Replaces a variable in a Unix shell with the substitute method, replacing the $foo in the string template with the passed in parameter foo
  2. Example:
           
          
    The code is as follows Copy Code
    1:#从string模块中导入Template
    
    2:&gt;&gt;&gt; fromStringImportTemplate3:#创建模板
    
    4:&gt;&gt;&gt; MyFormat = Template ("My name is $name")5:#替换变量并打印
    
    6:&gt;&gt;&gt;Print(Myformat.substitute (name="Bill Gunn."))7:My Name isBill Gunn8:&gt;&gt;&gt;9:
    
    Ten:#输出美元符号的方法, enter two $ in the template
    
    One :&gt;&gt;&gt; MyTemplate = Template ("The price is $$ $price")A :&gt;&gt;&gt; Mytemplate.substitute (price=100):' The price is $ '
    
    :&gt;&gt;&gt;:
    
    :#如果参数与后面的字符串相连, you need to enclose it in curly braces.
    
    :&gt;&gt;&gt; fromStringImportTemplate:&gt;&gt;&gt; MyTemplate = Template ("It ' s ${x}tastic!"):&gt;&gt;&gt; Mytemplate.substitute (x=' Slum '):"It ' s slumtastic!"
    
    :&gt;&gt;&gt;:
    
    To :#使用字典替换参数
    
    :&gt;&gt;&gt; MyTemplate = Template ("My $property is $value"):&gt;&gt;&gt; name = {}Num:&gt;&gt;&gt; name["Property"] ="Name"
    
    :&gt;&gt;&gt; name["Value"] ="Bill Gunn."
    
    :&gt;&gt;&gt; Mytemplate.substitute (name):' My name is Bill Gunn '
    
    :&gt;&gt;&gt;:
    3String formatting: Full version
  1. Description: The right-hand operand of the string format operator if it is a tuple, then each element in the tuple must have a corresponding escape specifier in the format string.
  2. Example:
          
         
    The code is as follows Copy Code
    1:&gt;&gt;&gt; data =tuple(List("123"))2:&gt;&gt;&gt; data3:(' 1 ',' 2 ',' 3 ')4:#格式化字符串中只有一个转义说明符, and there are three elements in the tuple, the conversion will complain
    
    5:&gt;&gt;&gt;Print(' data is%s '% data)6:Traceback (most recent call last):7:File"<pyshell#18>", Line 1, in&lt;module&gt;8:    Print(' data is%s '% data)9:TypeError: not  AllArguments converted during string formattingTen:#显示元组中的全部元素
    
    One :&gt;&gt;&gt;Print(' data is%s %s '%s '% data)A :Data is1 2 3:&gt;&gt;&gt;:
    3.1Conversion descriptor
  1. Conversion descriptor
     
    Escape Descriptor meaning
    D,i Signed decimal integer
    O Octal with no sign
    U Decimal with no sign
    X hexadecimal with no symbol (lowercase)
    X hexadecimal with no symbol (uppercase)
    E Floating-point number of scientific counting method (lowercase)
    E Floating-point numbers of scientific notation (uppercase)
    F,f Decimal floating-point numbers
    G If the exponent is greater than-4 or less than the precision, the same as E, otherwise the same as F
    G If the exponent is greater than-4 or less than the precision, the same as E, otherwise the same as F
    C Given (accept integer or single character string)
    R String (convert any Python object using repr)
    S String (convert any Python object using str)

3.2 Simple conversion

  1. Example:
           
          
    The code is as follows Copy Code
    1:   #十进制整数
    
    2:   Print ("The $%d" %)
    
    3:    is $
    
     4:  
    
     5:  #十六进制整数
    
    6:   Print ("Hex%x" %)
    
    7:   Hex C
    
     8:  
    
      
    
    9: #八进制整数 print   ("Oct%o" %)
    
    :  Oct
    
      >>>
    
     :  
    3.3Field width and precision
  1. Description
    1. Field width: The minimum number of characters retained by the converted value;
    2. Field Precision: The number of decimal places that should be in the result after conversion;
    3. can use * as field width or precision
  2. Example:
           
          
    The code is as follows Copy Code
    1:   #限制宽度
    
    2:   "%10f" % Math.PI
    
     3:  '  3.141593 '
    
     4:  
    
     5:   #限制小数位数
    
    6:   "%5.2f" % Math.PI
    
     7:  ' 3.14 '
    
     8:  
    
     9:   #用星号限制宽度和精度, in the following example, the width is 10 and the precision is 5
    
    . Ten:   '%*.*s ' ' Adfasdfadsfasdfasdfasdf ')
    
    One :   '     Adfas '
    
    A :   >>>
    
    :  
    3.4symbols, alignment, and 0 padding
  1. Description
    1. 0: The width is not enough with the number 0 fill;
    2. Minus sign: Left alignment;
    3. PLUS sign: Signs are marked either as positive or negative
    4. Space: Fill with space when the width is not enough;
  2. Example:
           
          
    The code is as follows Copy Code
    1:#空白补0
    
    2:&gt;&gt;&gt;Print("%010f"% Math.PI)3:003.1415934:
    
    5:#左对齐
    
    6:&gt;&gt;&gt;"%-10.2f"% Math.PI7:' 3.14 '
    
    8:
    
    9:#空白右对齐
    
    Ten:&gt;&gt;&gt;Print("% 5dn% 5d"% (123, 12))One :123A :12:
    
    :#显示正负符号
    
    :&gt;&gt;&gt;Print("%+5dn%+5d"% (123,-123)):+123:-123:&gt;&gt;&gt;:
    4String method

4.1 Find

  1. Description: Used to find substrings in long strings and, if found, returns the first occurrence of the substring on the left and no return-1, when looking, you can also specify the range to look for in long strings, providing the starting index and end index as the parameter for the lookup;
  2. Note: When looking, include the starting index position, but excluding the location of the end index;
  3. Example:
           
          
      code is as follows copy code
     1:  >>> String.ascii_letters  2:   ' abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz '   3:  >>> letters = string.ascii_letters  4:  &G T;>> letters.find ( ' AB ' )  5:   6:  >> ;> letters.find ( ' X ' , 30,-1)  7:   8:  >> ;> Letters.find ( "AB" , num)  9:  10:  
    4.2Join
  1. Description: Concatenate the elements in the queue with strings, and the elements in the list must be strings;
  2. Example:
     
            
           
      code is as follows
    1: >> > data = list ( ' 123456 ' ) 2: >>> data 4: >>> "AB" . Join (data) 5: ' 1ab2ab3ab4ab5ab6 ' 6: >>>
    7:

4.3 lower

  1. Note: Converts the string to lowercase letters and returns, but the original string does not change;
  2. Example:
     
            
          
      code is as follows
    < Span class= "Linenr" > 1:  >>> mystr=  "ABCD"   2:  >>> Mystr.lower ()  3:   ' ABCD '   4:  >>> mystr Span class= "Linenr" > 5:   ' ABCD '  6:  >>>  
    4.4 replace
    1. Description: Returns the string after which all occurrences have been replaced
    2. Example:
          
              
             
      The code is as follows Copy Code
      1:   "My name is Geng Qi"
      
      2:   >>> mystr.replace ("Geng Qi""Bill Gunn")
      
      3:  ' My name is Bill Gunn '
      
      4:  >>>
      4.5 Split
  1. Description: Split the string into a sequence;
  2. Note: If you do not provide a delimiter, whitespace is treated as a separator;
  3. Example
           
          
    The code is as follows Copy Code
      #以加号为分割符   2:  >>> MyStr =  1+2+3+4+5+6   3:  >>> mystr.split ( ' + ' )  4:  [ ' 1 ' ,  ' 2 ' ,  ' 3 ' ,  ' 4 ' ,  ' 5 ' , span> ' 6 ' ]  5:   6:   #不提供分割符时, with whitespace as separator  
                
                  7:  >>> mystr = 
                  "This is a test string"  
                  8:  >>> mystr.split () 
                  9:  [
                  ' This ' , 
                  ' is ' , 
                  ' a ' , 
                  ' test ' , 
                  ' string '  ' 
                 10:  >>> 
                 11:  
                
    4.6Strip
  1. Note: Remove both sides of the blank, you can also remove the specified characters;
  2. Example:
           
          
    The code is as follows Copy Code
    1:   "           asdfad adfasf asdf                      "
    
     2:  >>> mystr
    
     3:  '     Tasdfad adfasf asdf       tt '
    
     4:  #去除空白符
    
    5:  >> > Mystr.strip ()
    
     6:  ' asdfad adfasf asdf '
    
     7:  
    
     8:   #去除指定字符
    
    9:   >>> Mystr.strip (' t ')
    
    :  '     tasdfad adfasf ' asdf       '
    
    One :    a
    
    :  
    4.7Translate
  1. Description: Translate is a word substitution, you can replace multiple characters at the same time
  2. Example:
     
            
          
      code is as follows
    < Span class= "Linenr" > 1:  >>> table =  str . Maketrans ( ' CS ' ,  ' KZ '  ') Span class= "Linenr" > 2:  >>> table  3:  {115:122, 99:107}  4:  >>> " please don t knock at my door! .
    
    Translate (table)  5:   "Pleaze don ' t Knokk at my door!"  6:  

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.