Review the string knowledge points in Python

Source: Internet
Author: User
string

It is very easy to create a string object in Python. As soon as you put the required text in a pair of quotes, a new string is created (see Listing 1). If you think about it, you may feel a little confused. After all, there are two types of quotes that you can use: Single quotation marks (') and double quotation marks ("). Fortunately, Python once again solves this problem. You can use any class of quotation marks to represent a string in Python, as long as the quotation marks are consistent. If the string starts with a single quotation mark, it must end with a single quotation mark and vice versa. If you do not follow this rule, a SyntaxError exception will occur.
Listing 1. Create a string in Python

>>> sr= "Discover python" >>> type (SR)
 
  
   
  >>> sr= ' Discover python ' >>> Type (SR)
  
   
    
   >>> sr= "Discover python:it ' s wonderful!"    >>> sr= ' Discover python ' File '
   
    
     
    , line 1  sr= ' Discover python '            ^syntaxerror:eol while Scanning single-quoted string>>> sr= "Discover Python: \ ... It ' s wonderful! " >>> print Srdiscover python:it ' s wonderful!
   
    
  
   
 
  

As you can see from Listing 1, there are two other important aspects in addition to strings enclosed in appropriate quotes. First, when you create a string, you can mix single and double quotes, as long as the string uses the same type of quotation marks at the start and end positions. This flexibility allows Python to easily retain regular text data, which may need to use single quotation marks to denote shorthand verb forms or affiliation, and to use double quotation marks to denote quoted text.

Second, if the string is a line that is too long, you can use the Python sequential character: backslash (\) to wrap the string. From an internal mechanism, newline characters are ignored when creating strings, as can be seen when printing a string. You can use these two features together to create a string with a longer paragraph, as shown in Listing 2.
Listing 2. Creating Long strings

>>> passage = ' When using the Python programming language, one must proceed \ ... with caution. This is because Python are so easy to use and can be as so \ ... much fun. Failure to follow this warning may leads to shouts of ... "Woohoo" or "Yowza". ' >>> print Passagewhen using the Python programming language, one must proceed with caution. This is because Python are so easy-to-use, and can-be-much fun. Failure to follow this warning may leads to shouts of "Woohoo" or "Yowza".

Editor's note: the example above has been wrapped to make the page layout more reasonable. In fact, it would have been shown as a longer line.

Note that when you print the passage string, all formatting is deleted, leaving only a very long string. In general, you can use controls to represent simple formatting in a string. For example, to indicate that a new line starts, you can use a newline control (\ n), or you can use the tab control (\ t) to insert a tab character (the number of preset spaces), as shown in Listing 3.
Listing 3. Using a control character in a string

>>> passage= ' \twhen using the Python programming language, one must proceed\n\ ... \twith caution. This is because Python are so easy-to-use, and\n\ ... \tcan be so much fun. Failure to follow this warning may lead\n\ ... \tto shouts of "Woohoo" or "Yowza". ' >>> print Passage when using the-the Python programming language, one must proceed with caution. This is because Python are so easy-to-use, and can-be-much fun.  Failure to follow this warning may leads to shouts of "Woohoo" or "Yowza" .>>> passage=r ' \twhen using the Python Programming language, one must proceed\n\ ... \twith caution. This is because Python are so easy-to-use, and\n\ ... \tcan be so much fun. Failure to follow this warning may lead\n\ ... \tto shouts of "Woohoo" or "Yowza". ' >>> print Passage\twhen using the Python programming language, one must proceed\n\\twith caution. This is because Python are so easy-to-use, and\n\\tcan are so-much fun. Failure to follow this warning may lead\n\\Tto shouts of "Woohoo" or "Yowza". 

The first paragraph in Listing 3 uses the control in the way you expect. The paragraph is well-formed and easy to read. The second example, although also formatted, refers to the so-called original string, which is a string that does not have a control applied to it. You can always recognize the original string because the starting quotation mark of the string is preceded by an R character, which is the abbreviation for RAW.

I don't know what you are talking about, although this approach works, creating a paragraph string seems very difficult. Of course there must be a better way. As always, Python provides a very simple way to create a long string that preserves the format used to create the string. This method uses three double quotation marks (or three single quotes) to start and end a long string. In this string, you can use any number of single and double quotation marks (see listing 4).
Listing 4. A string with three quotes

>>> passage =     "" "... When using the Python programming language, one must proceed ...     With caution. This is because Python are so easy to use, and ...     Can is so much fun. Failure to follow this warning could lead ...     To shouts of "Woohoo" or "Yowza" .... "" ">>> print passage when            using the Python programming language, one must proceed with    caution. This is because Python are so easy-to-use, and can-be-    much fun. Failure to follow this warning may leads to    shouts of "Woohoo" or "Yowza".

Use a string as an object

If you read any of the articles in the first two articles of this series, you will immediately come to the bottom of the line in your mind: in Python, all things are objects. So far, I have not touched on the object characteristics of strings in Python, but, as always, the strings in Python are objects. In fact, a string object is an instance of the Str class. As you can see in the 2nd part of exploring Python, the Python interpreter includes a built-in Help tool (shown in Listing 5) that provides information about the Str class.
Listing 5. Get help information about strings

>>> Help (str) to the class str in     module __builtin__:          class str (basestring) | Str (object), String| | Return a nice string representation of the object.| If The argument is a string and the return value is the same object.| | Method resolution order:|   str|   Basestring|   object| | Methods Defined here:| | __add__ (...) |   x.__add__ (y) <==> x+y| ...

Strings created using single quotes, double quotes, and triple quotation marks are still string objects. However, you can also use the Str class constructor to explicitly create a string object, as shown in Listing 6. The constructor can accept simple built-in numeric types or character data as parameters. Both methods can change the input content to a new string object.
Listing 6. Create a string

>>> Str ("Discover python") ' Discover python ' >>> str (12345) ' 12345 ' >>> str (123.45) ' 123.45 ' >>> "Wow," + "that" + "is awesome." Wow, that's awesome. ' >>> "Wow," "that" "is Awesome" ' Wow, that's Awesome ' >>> "wow!" "Wow!" wow! wow! wow! wow! ' >>> sr = str ("Hello") >>> ID (SR) 5560608>>> SR + = "World" >>> SR ' Hello World ' >> > ID (SR) 3708752

The example in Listing 6 also shows several other important aspects of the Python string. First, you can create new strings by adding other strings together, either by using the + operator or by simply using the appropriate quotation marks to connect the strings together. Second, if you need to repeat a short string to create a long string, you can use the * operator to repeat the string a certain number of times. As I said at the beginning of this article, in Python, the string is a constant sequence of characters, and the last few lines in the previous example illustrate this, I first create a string and then modify it by adding another string. As you can see from the output of the ID method two call, the result of adding text to the original string is saved in the new string object created.

The Str class contains a number of useful methods for manipulating strings. You can use the Help interpreter to get information about this. Now let's take a look at four useful functions and demonstrate tools for other Str class methods. Listing 7 illustrates the upper, lower, split, and join methods.
Listing 7. String method

>>> sr = "Discover python!" >>> sr.upper () ' DISCOVER python! ' >>> sr.lower () ' Discover python! ' >>> sr = "This is a test!" >>> sr.split () [' This ', ' is ', ' a ', ' test! '] >>> sr = ' 0:1:2:3:4:5:6:7:8:9 ' >>> sr.split (': ') [' 0 ', ' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 ']>> ;> sr= ":" >>> tp = (' 0 ', ' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 ') >>> sr.join (TP) ' 0:1:2:3:4:5:6:7:8 : 9 '

The first two methods upper and lower are easy to understand. They simply convert the strings to uppercase or lowercase letters, respectively. The split method is useful because it can divide a string into several smaller string sequences by using the token character (or any character in a given sequence of characters) as an indicator of the location of the break. Therefore, the first Split Method example uses the default token to split the string "This is a test", which can be any white space character (this sequence includes spaces, tabs, and line breaks). The second split method demonstrates how to divide a string into a series of strings using a different token character (in this case, a colon). The last example shows how to use the Join method, which, in contrast to the split method, enables multiple short string sequences to form a long string. In this example, a colon is used to concatenate a sequence of strings consisting of a single character into a tuple.

Use a string as a container for characters

In the beginning of this article, I emphasize that the string in Python is a constant sequence of characters. The 2nd part of this series explores Python, and part 2nd describes the tuple, which is also a constant sequence. Tuple supports accessing elements in a sequence by using index symbols, separating elements in a sequence with fragments, and by using specific fragments or adding different fragments together to create a new tuple. Depending on the situation, you might want to know if you can apply the same technique to a Python string. As shown in Listing 8, the answer is clearly "yes".
Listing 8. String method

>>> sr= "0123456789" >>> sr[0] ' 0 ' >>> sr[1] + sr[0]  ' ten ' >>> Sr[4:8]   # Give Me Elements four through seven, inclusive ' 4567 ' >>> sr[:-1]   # Give me all elements but the last one ' 012345678 ' ;>> Sr[1:12]  # Slice More than you can chew, no problem ' 123456789 ' >>> sr[:-20]  # Go before the star T? ' >>> sr[12:]   # Go past the end? ' >>> Sr[0] + sr[1:5] + Sr[5:9] + sr[9] ' 0123456789 ' >>> sr[10]traceback (most recent call last): File "
  
   
    
  ", line 1, in? Indexerror:string index out of Range>>> Len (SR)   # Sequences has common methods, like get my length10
 /c7>
   
  

In Python, it is very simple to process a string as a sequence of characters. You can get a single element, add different elements together, cut out several elements, and even add different fragments together. A very useful feature of slicing is that making more slices before or after the start does not throw an exception, but starts or ends the sequence accordingly. Conversely, if you try to access a single element using an index that is outside the allowed range, you get an exception. This behavior illustrates why the Len method is so important.

Strings: Powerful Tools

In this article, I introduced the Python string, which is a constant sequence of characters. In Python, you can easily create strings using multiple methods, including using single quotes, double quotes, or more flexible, even with a set of three quotation marks. Assuming that everything in Python is an object, you can use the underlying STR class method to get additional functionality or sequence functionality that directly uses strings.

  • 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.