"Learning Python with You Hand in Hand" 7-Index of Strings

​In the last article "Learning Python with You Hand in Hand" 6-String Identification , we have a preliminary understanding of string identification methods and the use of special escape characters. Next we will learn a very important feature of strings-indexing and slicing.

Understanding the indexing principles and slicing methods of strings is not only the core of string operations, but also very helpful for us to learn about indexing and slicing of lists and other more complex data structures in the future.

Because when we index and slice a string, we generally do not directly operate on the string, but first assign the string to a variable, and then index and slice the variable.

So, before introducing strings, let's briefly understand the concept of variables.

A variable, as the name implies, is an amount that can be changed, or a value that can be changed. Corresponding to constants, that is, fixed values, such as a number, a string, pi, etc., are all constants, and their values ​​will not change due to the running of the program.

The variable is different. As the program runs, the value of the variable will continue to change. This change may be a change of artificial assignment, for example, let a equal to 1, and then let a represent 2, or it may be a need for program operation, such as in a loop, let the value of a automatically change, etc.

In short, the value of a variable can be changed.

The easiest way to change it is to assign, the assignment symbol is "=". The left side of "=" is the variable name, and the right side is the value assigned to the variable. For example: a = 1, b = 5, c ='abc', d ='Hello World!'. (When writing code, it is a customary habit to put a space on each side of the "=")

Because the variable has already been assigned, when we print Hello World!, we can either write print('Hello World!') or print(d).

Note that the d here is not quoted, otherwise it will become the string'd', which is not the variable d representing'Hello World!'.

Knowing the concept of variables, you can start indexing and slicing strings.

You will see in a while, in fact, the concepts and methods of indexing and slicing are not difficult, or even very simple. But if we really want to dig out the rules and be able to accurately judge the results under different changes, we need to have a deep understanding of the rules of indexing and slicing, especially for slicing.

In order to make this part of the basic but very important content clear, and to demonstrate clearly the examples of different situations, the index and slice will be divided into two articles to write.

Let's first understand the index in this article.

The so-called "index", you can first understand it as a catalog of books. Indexing a specific position of a character string and the content corresponding to this position is like looking for the page number of a book and the content corresponding to this page number through a table of contents.

However, there are two differences. One is that the table of contents of the book is marked with the page number from the first page, and the string starts from the 0th position. The second is that the book’s table of contents only has a page number sequence starting from 1 in one direction, and the character string can also start from the last 0 in addition to the last -1.

From the figure below, you can intuitively see the position and encoding of each character in the string.

With the basis of this picture, the next steps are very easy.

In [1]: str = 'Hello World!'

In [2]: str[0]
Out[2]: 'H'
​
In [3]: str[-1]
Out[3]: '!'

From the above example, you can see that indexing is the process of finding the corresponding content of the position code according to the position code of the string. This code can either use positive numbers counting from left to right (including 0), or you can choose negative numbers counting from right to left, depending on the purpose of writing the code.

In [4]:str[0].lower()
Out[4]:'h'
​
In [5]:str[-12].lower()
Out[5]:'h'

For example, if I want to change the uppercase letter at the beginning of a sentence to lowercase, I need to use position 0, counting from left to right. Of course, if the string is relatively short, the same effect can be achieved by using the position -12 counting from right to left, but this is generally not done.

Here to explain, sometimes for the convenience of examples, some content that has not been involved may be used. On the one hand, I will try to avoid this situation from happening. On the other hand, I will explain this part of the content. If there is something that I can’t understand It doesn't matter, there will be more detailed instructions in future articles.

The lower() here means to change the corresponding character to lowercase.

In addition, you may see that neither of the previous two examples uses the print() function. This is because in Jupyter Notebook, you can directly output the results of the operation without printing each time, but the output results will be different.

For example, in the above example, if the print() function is used, the output result h does not include the two single quotes ".

In [6]: print(str[0].lower())
Out[6]: h

This is because, as in the previous article, single quotes, double quotes, or triple quotes are all string identifiers, not a part of the string, and have no real meaning, so they will not be printed.

If it is not particularly necessary, for the sake of simplicity of the program and intuitive results, in the following examples, the print() function is not used by default to print the results.

Continue to the index above.

Although we just changed the uppercase letter at the beginning of the sentence to lowercase, we did not change the first letter in the string "Hello World!" Lowercase'h'. It can be verified by the following code:

In [7]: str
Out[7]: 'Hello World!'

The string itself has not been modified, this is because the string is constant and immutable!

If you want to change the ending "!" to ".", you can use the -1 position counting from right to left, or the 11 position counting from left to right, but everyone should already know the result and an error will be reported.

In [8]: str[-1] = '.'
Out[8]: ---------------------------------------------------------------------------
        TypeError                                 Traceback (most recent call last)
        <ipython-input-8-cba0631dd81c> in <module>
        ----> 1 str[-1] = '.'
​
        TypeError: 'str' object does not support item assignment
​
 In[9]: str[11] = '.'
Out[9]: ---------------------------------------------------------------------------
        TypeError                                 Traceback (most recent call last)
        <ipython-input-9-c89a1731b99d> in <module>
        ----> 1 str[11] = '.'
​
        TypeError: 'str' object does not support item assignment

The above is the whole content of the string index, the key point is to understand the representation method of the string index position.

In the next article, we will learn about the slicing method of strings.

 

 


Thanks for reading this article! If you have any questions, please leave a message and discuss together ^_^

Welcome to scan the QR code below, follow the "Yesu Python" public account, read other articles in the "Learning Python with You Hand in Hand" series, or click the link below to go directly.

"Learning Python with You Hand in Hand" 1-Why learn Python?

"Learning Python with you hand in hand" 2-Python installation

"Learning Python with You Hand in Hand" 3-PyCharm installation and configuration

"Learning Python with You Hand in Hand" 4-Hello World!

"Learning Python with You Hand in Hand" 5-Jupyter Notebook

"Learning Python with You Hand in Hand" 6-String Identification

For Fans: Follow the "also said Python" public account, reply to "Hand 7", you can download the sample sentences used in this article for free.

Also talk about Python-a learning and sharing area for Python lovers

 

Guess you like

Origin blog.csdn.net/mnpy2019/article/details/98755114