Free Python course. Sign Up for tracking progress →

Python: Forming Strings in Loops

You can also use loops to form strings. This is often needed during web programming. It all comes down to the usual aggregation when interpolation or concatenation is applied.

You'll often be asked to write a program to reverse a string in interviews. The correct way to flip a string is to use a function from the standard library. But it's important to know how to actually implement it yourself.

One of the algorithms looks like this:

  1. Build a new string

  2. 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 through 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 (remember indexes start with zero)
  • reversed_string = '' - initialize the string that we'll write the result to
  • while index >= 0: - condition: repeat the body of the loop until the current index reaches 0 - (the first character)
  • current_char = string[index] - take the character at the current index from the string
  • reversed_string = reversed_string + current_char - write the new value to the string with the result: current string is the result + the new character
  • index = index - 1 - update the counter
  • return reversed_string - when the loop is done, return the result string

We advise you to copy this function into the REPL https://replit.com/languages/python3 and experiment with it a little.

When working with strings, programmers often make the mistake of going past string boundaries. If a wrong initial counter value is chosen or a mistake is made in a loop predicate, the function may access a character that doesn't exist.

It's also extremely often forgotten that the index of the last element is always one less than the size of the string. In strings, the initial index is 0, so the index of the last element is len(str) - 1.

Instructions

Implement a function called my_substr() that extracts a substring of a specified length from a string. It takes two arguments as input: a string and a length, and returns a substring starting from the first character:

Call example:

string = 'If I look back I am lost'
print(my_substr(string, 1)) # => 'I'
print(my_substr(string, 7)) # => 'If I lo'

Use the same approach as in the function to flip the string from the lesson: assemble the resulting string with a loop by looping over the initial string to a certain point.

This problem can be solved using slicing. But in this exercise, we want to practice using loops, so we'll implement this functionality ourselves. Slice syntax essentially uses loops anyway.

The exercise doesn't pass checking. What to do? 😶

If you've reached a deadlock it's time to ask your question in the «Discussions». How ask a question correctly:

  • Be sure to attach the test output, without it it's almost impossible to figure out what went wrong, even if you show your code. It's complicated for developers to execute code in their heads, but having a mistake before their eyes most probably will be helpful.
In my environment the code works, but not here 🤨

Tests are designed so that they test the solution in different ways and against different data. Often the solution works with one kind of input data but doesn't work with others. Check the «Tests» tab to figure this out, you can find hints at the error output.

My code is different from the teacher's one 🤔

It's fine. 🙆 One task in programming can be solved in many different ways. If your code passed all tests, it complies with the task conditions.

In some rare cases, the solution may be adjusted to the tests, but this can be seen immediately.

I've read the lessons but nothing is clear 🙄

It's hard to make educational materials that will suit everyone. We do our best but there is always something to improve. If you see a material that is not clear to you, describe the problem in “Discussions”. It will be great if you'll write unclear points in the question form. Usually, we need a few days for corrections.

By the way, you can participate in courses improvement. There is a link below to the lessons course code which you can edit right in your browser.


If you got stuck and don't know what to do, you can ask a question in our community