Is it just me, or were strings in python supposed to be difficult?

Title says it all. I’m currently struggling to understand the last few parts of the exercise. Most of it had to do with my inability to know when to use the for loop when defining a function. Anyone else find themselves stuck at this stage?

Hi there, welcome to the community!

Can you post a link to the exercise you found difficult? Some of the material may be challenging, sure, but I doubt any of it was meant to be deliberately tricky. :slight_smile:

https://www.codecademy.com/courses/learn-python-3/lessons/introduction-to-strings/exercises/review-i
like when should I iterate through strings? I think those 2 problems provide a good example of my dilemma as to choosing which approach is best in answering both questions.

This is one of those questions where the answer is really “it depends on what you’re trying to accomplish”.

Broadly speaking, for many of the tasks in the Codecademy lessons you can usually get a reasonable idea of how to approach the task by thinking “how would I do this?”

By this, I mean thinking about how you as a human being would complete the task and ignore how the computer should do it for the moment.

Let’s say we were working on the following problem:

Does the word cheesecake contain the word see?

As a human, we’d just scan along the word cheesecake and if we saw the word see we’d say “Yep, it’s there!” or “Nope!” if it’s not.

This is a pattern we can replicate in Python. There’s a few ways of doing it, but the easiest is to use the in operator.

def big_word_little_word(big_word, little_word):
    if little_word in big_word:
       return True

    return False

If the little_word is in the big_word, we return True; otherwise, we return False. We can do this without having to iterate thanks to the in operator.

On the other hand, if we wanted to do something like implementing a Caesar cipher then we would need to iterate over the string because the process we’d follow as a person would be:

  1. Look at the letter
  2. Work out the letter 3 steps further in the alphabet (e.g. if we’re looking at A, we’d go three further and get D)
  3. Write the new letter.
  4. Repeat.

If you can work out how to do the task as a person, and work out the individual steps that you take as part of solving it, you can “map” those steps to a programming construct. :slight_smile:

You’ll also find that as you become more familiar with Python you can look at previous solutions where perhaps you’ve taken a longer approach (like iterating over a string to see if a particular substring is present) and see ways to improve it by making it shorter/quicker. :slight_smile:

2 Likes

Hello @cratox ,

Strings can get tricky. I think it helps to work/play with it more.

Here’s more info on it:
String Manipulation in Python - PythonForBeginners.com

2 Likes