Python Forum

Full Version: Using for loops and indexing to read and string and print only select words
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have set out to use a for loop using indexing to print out only the words that start with an s in this sentence: "Secret agents are super good at staying hidden."

Here is the code I wrote:
mystring = "Secret agents are super good at staying hidden."
mystring.split()
for i in mystring:
    if mystring[0] == 'S' or 's':
        print(i)
To explain this code, here I take the string and split each word up. Then I iterate or cycle through each item. If the first letter of each item is an ‘S’ or ‘s’, only that word should be printed.

Therefore, I was expecting this output:

Quote:Secret
super
staying

But instead I got:

Quote:S
e
c
r
e
t

a
g
e
n
t
s

a
r
e

s
u
p
e
r

g
o
o
d

a
t

s
t
a
y
i
n
g

h
i
d
d
e
n

Can someone explain better what my code is actually doing and what I need to do to produce the expected output?

For my reference, this forum post refers to Task #1 in Jose Portilla’s so called 04-Field-Readiness-Exam-2 in his “Narrative Journey” Udemy Python course material (on GitHub: Pierian-Data/Python-Narrative-Journey).
line 2, change it to
mystring = mystring.split() # use different variable name if you want to keep original mystring
then for the error on line 4 read https://python-forum.io/Thread-Multiple-...or-keyword. Also note that you want to check that i (change this name to something meaningful like word) starts with s. finally it's recommended to use str.starstwith() method, not slicing:
Quote:Use ''.startswith() and ''.endswith() instead of string slicing to check for prefixes or suffixes.

startswith() and endswith() are cleaner and less error prone:

Yes: if foo.startswith('bar'):
No: if foo[:3] == 'bar':
Thank you for your reply, @buran.

I've changed the iterable from i to word because it is more meaningful as you've suggested.

I’ve also rewritten my code snippet, this time using the str.startswith(prefix[, start[, end]]) builtin documented on python.org.

Also, thank you for sharing the link which refers to the way I have used my disjunction. It's verified as a boolean (either True or False), which is not what I am trying to do here. Even after reading your forum thread on Multiple expressions with "or" keyword, at this point I’m still not quite so sure I understand enough how to verify both ’s’ and ’S’, so for now my new code snippet is just going to process the words which begin with only ‘s’. Here is my updated code sample:

mystring = "Secret agents are super good at staying hidden."
secondstring = mystring.split()
# desired_characters = ('s')
for word in secondstring:
    desired_character = ('s')
    if secondstring.startswith(desired_character[0]):
        print(word)
    break
Here is my traceback:
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-49-6eba6228d5b9> in <module>()
      4 for word in secondstring:
      5     desired_character = ('s')
----> 6     if secondstring.startswith(desired_character[0]):
      7         print(word)
      8     break

AttributeError: 'list' object has no attribute 'startswith'
The traceback is now pointing to an issue with line 6. I’m calling the startswith() method incorrectly because I am missing an attribute. I think I’m misreading the startswith() Python doc that was linked to earlier but I am not sure exactly what I am missing. Can someone please clarify?
you want to check that word starts with s not the list
mystring = "Secret agents are super good at staying hidden."
words = mystring.split()
desired_characters = ('s', 'S')
for word in words:
    if word.startswith(desired_characters):
        print(word)
Output:
Secret super staying