Creation and Use of Strings in Python. Mastery 26.

A string is a sequence of characters. You can access the characters one at a time with the bracket operator.

Per example, let’s declare a string variable called car containing a sequence of characters forming the word mazda6.

In this example I’m calling the character corresponding to the third value of index of characters. Remember that the index starts at 0, so the character 0 will be c, the character 1 a, the character 2 z and so on.

Len.

The function len is able to return the numbers of characters contained in a string. Example:

 

If you want to get the last character of a string you can try something like this:

Traversal.

The process of dealing one string character at time and doing something to it, is called traversal processing.

Example:

This prints individually each of the characters contained inside the car string.

Slices.

Slices are segment of strings. Selecting slices of a certain strings is really easy.

Example:

The slice that I’m calling in this example is one going from the index 0 to the 4th index. Notice that using the 5 in the brackets means calling the previous character in the index. So the bracket works something like this [firstindex:lastindex+1].

Because…

Immutability.

Strings are immutable, that meaning that you are not able to change an existing string. The best thing you can do to deal with this is creating a new string that is a variation from the original.

Example, let’s call a new model ‘mazda3’:

You can appreciate that I’m calling the slice that contains the word ‘mazda’ and I’m adding a ‘3’ to the end, so I have a new string called new model containing the string ‘Mazda3’

Counting.

Also, you can go a little forward and count the times that a character appears in a string. Let’s count how many times the ‘a’ appears in ‘Mazda6’.

 

These are somes of the things that you can do with a string. Have fun 😀

 

 

26

CC BY 4.0 Creation and Use of Strings in Python. Mastery 26. by Ismael Lizárraga is licensed under a Creative Commons Attribution 4.0 International License.

Comments are closed.