Review Python string knowledge points and python string knowledge points

Source: Internet
Author: User

Review Python string knowledge points and python string knowledge points

String

It is very easy to create a String object in Python. You only need to put the required text in a pair of quotation marks to create a new string (see Listing 1 ). If you think about it, you may be confused. After all, there are two types of quotation marks available: single quotation marks (') and double quotation marks ("). Fortunately, Python once again solved this problem. You can use any type of quotation marks to represent strings in Python, as long as the quotation marks are consistent. If the string starts with single quotes, it must end with single quotes, and vice versa. If this rule is not followed, a SyntaxError error occurs.
Listing 1. Create a string in Python

>>> sr="Discover Python">>> type(sr)<type 'str'>>>> sr='Discover Python'>>> type(sr)<type 'str'>>>> sr="Discover Python: It's Wonderful!"    >>> sr='Discover Python" File "<stdin>", line 1  sr='Discover Python"            ^SyntaxError: EOL while scanning single-quoted string>>> sr="Discover Python: \... It's Wonderful!">>> print srDiscover Python: It's Wonderful!

From list 1, we can see that in addition to the strings enclosed by proper quotation marks, there are two important aspects. First, when creating a string, you can mix single quotes 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. These regular text data may need to use single quotes to represent abbreviated verb forms or associations, and use double quotes to represent quoted text.

Second, if a string is too long in one line, you can use the Python continuous character: backslash (\) to fold the string. From the internal mechanism, line breaks are ignored when a string is created, which can be seen when the string is printed. You can use these two functions together to create strings containing long paragraphs, as shown in Listing 2.
List 2. Create a long string

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

Editor's note: the preceding example has been processed in lines to make the page layout more reasonable. In fact, it is originally displayed as a long row.

Note: When the passage string is printed, all formats are deleted and only a very long string is retained. Generally, you can use a controller to represent a simple format in a string. For example, to start a new line, you can use the line feed controller (\ n); To insert a tab (default number of spaces), you can use the tab controller (\ t ), as shown in listing 3.
Listing 3. Using a controller in a string

>>> passage='\tWhen using the Python programming language, one must proceed\n\... \twith caution. This is because Python is 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 Python programming language, one must proceed    with caution. This is because Python is so easy to use, and    can be so much fun. Failure to follow this warning may lead    to shouts of "WooHoo" or "Yowza".>>> passage=r'\tWhen using the Python programming language, one must proceed\n\... \twith caution. This is because Python is 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 is 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".

The first section in listing 3 uses the control operator as expected. This section has a good format and is easy to read. In the second example, although formatting is also performed, it references the so-called original string, that is, the string without a control character. You can always recognize the original string because there is an r character before the start quotation mark of the string, which is short for raw.

I don't know what you are talking about. Although this method is feasible, it seems very difficult to create a paragraph string. Of course, there must be better methods. As usual, Python provides a very simple method for creating long strings, which can retain the format used when creating strings. This method uses three double quotes (or three single quotes) to start and end a long string. In this string, you can use any number of single quotes and double quotes (see Listing 4 ).
Listing 4. strings with three quotation marks

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

Use a string as an object

If you read any of the first two articles in this series, you will immediately see the following sentence in your mind: in Python, everything is an object. So far, I have not touched on the Object Features of strings in Python. However, as usual, strings in Python are objects. In fact, the string object is an instance of the str class. As you can see in explore Python, section 2nd, the Python interpreter includes a built-in help tool (as shown in listing 5) that provides information about the str class.
Listing 5. Getting help information about strings

>>> help(str)     Help on 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, the return value is the same object.| | Method resolution order:|   str|   basestring|   object| | Methods defined here:| | __add__(...)|   x.__add__(y) <==> x+y| ...

A string created using single quotes, double quotes, and three quotes is still a String object. However, you can also use the str class constructor to explicitly create a String object, as shown in Listing 6. This constructor can accept simple built-in numeric or character data as parameters. Both methods can change the input content to a New String object.
Listing 6. Creating strings

>>> str("Discover python")'Discover python'>>> str(12345)'12345'>>> str(123.45)'123.45'>>> "Wow," + " that " + "was awesome."'Wow, that was awesome.'>>> "Wow,"" that ""was Awesome"'Wow, that was Awesome'>>> "Wow! "*5'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 about Python strings. First, you can create a new string by adding other strings together. You can use the + operator in the specific method, or simply use 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 for a certain number of times. As I mentioned at the beginning of this article, in Python, strings are unchanged character sequences. The last few lines in the above example illustrate this. I first create a string, then, modify it by adding other strings. From the output of the two calls to the id method, we can see that the New String object is saved as the result of adding text to the original string.

The str class contains a large number of useful methods for operating strings. Here we will not describe them one by one. You can use the help interpreter to obtain relevant information. Now let's take a look at the four useful functions and demonstrate other str class methods. Listing 7 demonstrates 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 only convert the strings into uppercase or lowercase letters. 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 string) as an indicator of the disconnection position. Therefore, the first split method uses the default token to split the string "This is a test". This token can be any blank character (This sequence includes spaces, tabs, and line breaks ). The second split method demonstrates how to use different token characters (in this example, the colon is used) to split a string into a series of strings. The last example shows how to use the join method. This method is opposite to the split method. Multiple short string sequences can form a long string. In this example, a colon is used to connect the string sequences contained by a single character in the tuple.

Container that uses a string as a character

At the beginning of this article, I emphasize that strings in Python are character sequences that are unchanged. Part 1 of this series explores Python and Part 2 introduces tuple, which is also a constant sequence. Tuple supports accessing elements in a sequence by using index symbols, separating elements in a sequence by Using fragments, and creating new tuples by using specific fragments or adding different fragments together. Depending on this situation, you may wonder if you can apply the same technique to Python strings. As shown in listing 8, the answer is obviously "yes ".
Listing 8. String Method

>>> sr="0123456789">>> sr[0]'0'>>> sr[1] + sr[0]  '10'>>> 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 start?''>>> 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 "<stdin>", line 1, in ?IndexError: string index out of range>>> len(sr)   # Sequences have common methods, like get my length10

In Python, it is very easy to process strings as character sequences. You can obtain 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 it does not throw an exception when many slices are performed before or after the start, but starts or ends the sequence by default. Conversely, if you try to access a single element using an index outside the permitted range, an exception is returned. This behavior illustrates why the len method is so important.

String: A Powerful Tool

In this article, I introduced the Python string, which is a constant character sequence. In Python, you can easily create strings using multiple methods, including using single quotes, double quotes, or more flexible methods, that is, using a group of three quotes. Assuming that everything in Python is an object, you can use the underlying str class method to obtain additional functions or directly use the string sequence function.

Related Article

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.