Skip to content

Introduction to Python – Chapter 6 – Strings and For Loops

In this video, we’ll talk more about strings and explain the for loop.

A string is a data type created when we use a pair of quotation marks.

is an example of a string.

Let’s say that I wanted to get the “m” character in “microwavesam”.

A character is the term used for a single symbol in Python.

In Python and programming languages, we also use the term, element.

An element is a term for any individual part of a string.

To get a character in a string, you grab its index.

An index is a fancy term for a member of a set of parts.

For example, to get “m”, I could write,

bracket 0 bracket is the index.

The index is just a fancy term for a position in the string.

In Python and programming languages, the position of the first character starts at 0.

The reason why position starts at 0 is because an index represents the offset from the first character.

At the first character, I am 0 positions away from the starting position.

The first character is m. At the starting position, I am 0 positions away from the first character.

If I print first_letter, I will get an “m”.

When I run the program, I get the first_letter, which was at index 0.

I can get the second letter by assigning:

When I run the program, I also get the second letter, i, which was at index 1.

Just remember when getting a single character from a string while using an index, the first character’s index starts at 0.

Next thing that we’ll talk about is length of a string.

Python strings have a len function that allows you to get the length of a string measured in the number of characters.

If I write,

I will get the number of characters that make up “microwavesam”, which is 12.

The len function is very useful for getting the last character of the string.

If I wanted the last “m” in “microwavesam”, then use len_username – 1.

The last character’s index is 11 since the first chracter’s start position was 0, which means that the last character’s index is len_username – 1.

If I try to get the character at an index out of range, then I’ll get an IndexError.

For example,

I can try to get the index of username at length of username.

When I run the program, I get the IndexError, because there is no character at that index.

The last character’s index is len_username – 1. Not len_username.

Instead of using len_username – 1 to get the last character, we can use index, -1.

To get the second last character, -2. Keep decreasing the negative number index, to get the characters in reverse.

In the last video, we mainly talked about how iteration could be much easier with while loops since while loops can perform repetitive steps until its condition is false.

There’s another type of iteration called for loops.

A for loop visits each character of a string one at a time, and you can do something at each index or position that you visit.

Using for loops and while loops is called a traversal.

In a while loop, we have a variable that progresses, which eventually makes the while statement condition false.

Let’s say that we wanted to print each character of the username, “microwavesam”, 1 at a time.

index starts at 0 because the starting position is 0 elements away from the first character.

Now, I want to visit every element of microwavesam, so the condition that I want to end my function is when my index is greater than or equal to the length of microwavesam.

When the index is less than len(username), I can print the character at the current index.

Now, I need the index variable to progress, so that it eventually makes the condition false.

This while loop is visiting each character of the username variable.

At each index, we print the character until index is greater than or equal to the length of microwavesam since the last index would be len(username) – 1.

Remember that the last character of a string is len(username) – 1.

This while loop is an example of how a for loop works.

We can do visit every character in “microwavesam” with the for loop.

In this usage of a for loop, the for loop begins with the for keyword.

Then, I left the name of a variable, letter.

in is a keyword that means exactly what it implies.

Using letter in means at each step of the for loop, we are visiting the username’s characters 1 by 1.

In this for loop example, you don’t have to keep track of the condition of stopping at last character.

This for loop automatically will stop after visiting the last character of “microwavesam”.

The second way to do a for loop is by range. Sometimes, you only want to visit a certain number of characters like the first three characters.

Let’s say that I only wanted to visit “mic” from “microwavesam”

We use the for keyword and the in keyword again.

This time I use i as the variable name, short for index.

Then, after the in keyword, I use range(0, 3).

With range, you put the starting number. What will i be at the first step?

Then, each step will by default increase i by 1.

When, the i becomes 3, don’t do the steps in the for loop. The for loop is done.

In this for loop, we start at 0.

Increase i by 1. i = 1.

Increase i by 1. i = 2.

Increase i by 3. When i is 3, exit the for loop.

When we run the program, we will get “m”, “i”, and “c” each on a new line as expected.

If we wanted to print every character of the “microwavesam” with this way of writing a for loop.

We can easily change 3 to len(username).

When we run the program, we get every letter printed out in “microwavesam”.

You would use this type of for loop whenever you want to have more control over each step of your for loop.

For a better example on this for loop’s control, we can print out every other letter.

When you put an additional number inside the parentheses, that number is added to the variable at every step.

i will be increased by 2 at each step, which will allow us to visit every other number.

When we run the program, the for loop will visit every other letter in “microwavesam”.

You can make the range be flexible. We can go in reverse.

For example, we can start at the last index of the string. The last letter of the string.

When we run the program, we visit every character backwards. We start at the last “m”.

len(username) – 1 is the start position.

We are adding -1 to i each step.

When i is -1, we don’t run the statement in the for loop, and the for loop ends.

The third way you can use a for loop is with enumerate. enumerate allows you to get the index and the value as two usable variables.

For example, there are many situations where you’ll need both the index and the value, which is why you would use range.

But sometimes, typing the range may be bothersome, so you can use enumerate like this:

Let’s say that we wanted to print out both the index and value at the index.

You can place two variables that will get the index and value from that index when you use enumerate(username).

These three ways of using for loops provide you with the control to get exactly what you want from every step in the loop.

Now, you might be thinking, why should I use a for loop?

After all, a while loop can do the same thing as any for loop. Why not just remember how to do while loops?

The two main advantages of a for loop are locality and readability.

First, locality.

When we were creating a while loop, we created an index variable in the outside of the while loop.

When we create a for loop the variable is declared inside the for statement.

What happens to the variable declared in the for statement stays within the for loop.

If the variable was created in the outside of the loop like in a while loop, you or someone else might make a mistake in the future and use that variable by accident and cause problems.

Second, being specific. for loops are more readable.

You have a start position and an end position. The start and end positions are clearly defined in the for statement.

We’ve seen that the for statement does initialization, step, and completion condition all in one line.

In a while loop, the while statement has an end condition or completion condition.

The initialization and what to do at each step are located elsewhere.

A while loop is not as quickly readable as a for loop.

A for loop is great for counting up and down like going through each character in “microwavesam” or counting down to the New Year.

A while loop is better for conditions that do not involve counting like the difference between these two doubles must be less than 0.02.

I’m not counting up or down. I’m checking a difference, and I want to keep on tweaking the two numbers until the difference is less than 0.02.

A while loop would be better for that situation.

When you’re counting up and down, visiting through a step by step process that involves incrementing or decrementing numbers, think for loops.

When you have a condition that you must check, and you’re not necessarily counting up or counting down, think while loops.

Now that you understand for loops pretty well, let’s talk about string slicing.

A string slice is a term for a part of a string.

Instead of using a for loop to get the first 3 characters of a string, Python has an abbreviated form using the index numbers.

For example, to get the first 3 characters with string slicing:

Inside the brackets, you put the starting index position, then a colon, then 1 + ending position.

I don’t want to visit the character at index 3 because the character at index 3 is the 4th character.

The first number is inclusive. The second number is non inclusive.

When I run the program, I get “mic” all in one word. String slicing is great for getting entire segments of a string.

It makes getting a continuous part of a string much easier than using a for loop.

Let’s talk about how string are immutable.

Immutable is the term used when something cannot be changed.

In a previous video, we talked about how we could use the addition operator, +, to add two strings together.

A term for adding two strings together is concatenate.

For a string, you cannot change individual letters, which means if I wanted to assign a new letter for a word, I would get an error.

Instead of “microwavesam”, I want “microwavefam”.

When I run the program, I get an error about how the string or object doesn’t support item assignment.

Strings are immutable, which means that portions of a string cannot be reassigned and changed.

A little bit ago, I talked about how for loops are great for counting up and down.

Let’s do a for loop example with a counter.

A counter is a term used often in programming. It’s just a word used for variable that keeps count of something.

We can count the number of “m”‘s in “microwavesam”

We can use variables assigned outside of the for loop inside the for loop.

We can use conditionals like normally inside the for loop.

In this for loop, we check if the current character is equal to “m”.

If the char is equal to “m”, then we increase the count by 1.

When we run the program, we print out the number of “m”‘s, which is 2.

counters are useful variables that keep track of the number of anything inside a loop.

Searching. You can find a segment of a string by using the “in” keyword.

For example,

Using if string in a string can find whether a string is in another string.

“microwave” is inside “microwavesam”, so when we run the program,

“microwave in microwavesam” is printed out.

Instead of just finding a string in a string, we can also see if a string starts or ends with a certain string.

This is very useful if you expect a certain prefix and suffix.

With the .startswith(“”) and .endswith(“”), you can check whether a string starts with or ends with a certain string.

When I run the program, two Trues are printed out because username does start with “microwave”, and it does end with “sam”.

You can check a count of a letter in a string without using a for loop.

When I run the program I get a 2 like we did when using a for loop.

Using .count with a string finds how many of that string is inside “microwavesam”.

There are 2 m’s in “microwavesam”.

There are functions that can change the case like uppercase and lowercase.

Using .lower() makes the string all lowercase.
Using .upper() makes the string all uppercase.
Using .capitalize() makes the first letter capitalized.

Last but not least, there are functions for strings that allow you to replace substrings or take out white space.

You can replace a part of a string with something else. Think of the find and replace feature in most text editors.

When we run the program, “sam” is replaced with “bob”.

Occasionally, you’ll have a string with a lot of whitespace at the end of a string or in the beginning of a string.

You can take out all whitespace by using the .strip function.

When I run the program, all the white space has been stripped from the username variable, and I get “microwavesam”.

Those functions are the main functions that I would use when I have a string.


Video Demonstration