Coding3: Strings: Length, Concatenation, Indexing, and Slicing Part 2
Now Finishing up the Indexing and Slicing Sections. Highly recommend reviewing the part 1 before reading part 2, we use some of the materials from there.
Table of Contents:
String Indexing
Python
R
String Slicing
Python
R
String Indexing
Recall from our part 1 on strings that strings are a sequence of characters. Since they are a sequence, that means there is a starting position, and and ending position. The location at which a specific character is located in a string is called it’s index.
Python
Python starts counting it’s indexes from 0. This means that the first character in a string is located at the 0th position, the second character is located at the 1st position, and so on… In order to actually do the indexing, we use a square bracket: [ ].
In Python, the firsts character is located at index 0, and the last at -1.
In the below example, we make a string called ‘Mr. BowTied Oxie’, and do some basic indexing:
R
R does not have an indexing feature, however there is indeed a way to get a specific character, we will discus that in the string slicing below.
String Slicing
Python
If we wanted to print not just one letter at a time, but several based off of their positions. One simple way we can do this is to use concatenation and indexing at the same time. In this example, we print the first 3 characters of ‘Mr. BowTied Oxie’.
There is another alternative route we can take, and that is called using string slicing. The basic idea is if we have a string, we can slice it into several different substrings. The idea of course would be the take the original string, and slice it in such a way, so that the new substring we create is the one we are after. Take a look at the image below that gives you an idea of how the positions in indexing and slicing differ slightly.
I in this case represents indexing, and S represents slicing.
Note: From the above image, you can see that the index is located on top of the character, and the slicing is located between characters.
In order to actually do the slicing, we need to use the following format—> [starting:ending]. We do the above ‘Mr.’ example using slicing now:
R
In order to do both string indexing, and slicing, we will use the substr() function. The substring function is extremely simple, we simply indicate the positions of the characters we are interested in grabbing. So, in order to grab the first 3 characters similar to the above example, we would do substr(string1,1,3)
Astute readers at this point can already guess how we would do string indexing in R as well…
Here’s an example on how we can use substr in order to implement string indexing similar to the Python example above.
Recall from the Code 3: Part 1 post, R has a function called nchar() that tells us how many characters a string has.
Here is a visual for R:
Click Here to go to Coding4: Immutability & String Methods.