We use loops to work with strings as well as numbers. For example, you can get a specific character by its index and form strings in loops. In this lesson, we'll figure out how to do it.
How to get characters from indexes
Below is a sample code that prints the letters of each word on a separate line:
def print_name_by_symbol(name):
i = 0
# This check will run until the end of the string, including the last character
# Its index is `length - 1`
while i < len(name):
# Accessing the symbol by its index
print(name[i])
i += 1
name = 'Arya'
print_name_by_symbol(name)
# => 'A'
# => 'r'
# => 'y'
# => 'a'
The main thing in this code is to put the condition in the while
. We can do it in two ways:
i < len(name)
i <= len(name) - 1
They will lead to the same result.
How to form strings in loops
You can also use loops to form strings. We often need it during web programming. It all comes down to the usual aggregation when interpolation or concatenation is applied.
In a job interview, the interviewer can ask you to write a program to reverse a string. The correct way to do it is to use a function from the standard library. But it's important to know how to implement it yourself.
One of the algorithms looks like this:
Build a new string
Go through the characters of the original string in reverse order:
def reverse_string(string): index = len(string) - 1 reversed_string = '' while index >= 0: current_char = string[index] reversed_string = reversed_string + current_char # The same using interpolation # reversed_string = f'{reversed_string}{current_char}' index = index - 1 return reversed_string reverse_string('Game Of Thrones') # 'senorhT fO emaG' # Neutral element check reverse_string('') # ''
Let's analyze the function line by line:
index = len(string) - 1
— we write the index of the last character of the string into a new variable (indexes start with zero)reversed_string = ''
— we initialize the string that we will write the result towhile index >= 0:
— it is the condition. We repeat the body of the loop until the current index reaches the first character 0current_char = string[index]
— it takes a character from the string at the current indexreversed_string = reversed_string + current_char
— we write the new value into the resulting string, meaning current result string + new characterindex = index - 1
— we update the counterreturn reversed_string
— when the loop is over, we return the result string
When working with strings, programmers often make the mistake of overstepping string boundaries. If we choose the wrong initial counter value or make a mistake in a loop predicate, the function may access a character that doesn't exist.
It is also often forgotten that the index of the last element is always one less than the size of the string. In strings, the starting index is 0
, so the final element index is len(str) - 1
.