Python Forum
Using for loops and indexing to read and string and print only select words
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Using for loops and indexing to read and string and print only select words
#1
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).
Reply
#2
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':
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
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?
Reply
#4
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
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Formatting a date time string read from a csv file DosAtPython 5 1,296 Jun-19-2023, 02:12 PM
Last Post: DosAtPython
  Pulling Specifics Words/Numbers from String bigpapa 2 769 May-01-2023, 07:22 PM
Last Post: bigpapa
  [SOLVED] [BeautifulSoup] Turn select() into comma-separated string? Winfried 0 1,124 Aug-19-2022, 08:07 PM
Last Post: Winfried
  Remove a space between a string and variable in print sie 5 1,799 Jul-27-2022, 02:36 PM
Last Post: deanhystad
  Can you print a string variable to printer hammer 2 1,960 Apr-30-2022, 11:48 PM
Last Post: hammer
  Extract a string between 2 words from a text file OscarBoots 2 1,882 Nov-02-2021, 08:50 AM
Last Post: ibreeden
  Print first day of the week as string in date format MyerzzD 2 2,030 Sep-29-2021, 06:43 AM
Last Post: MyerzzD
  Generate a string of words for multiple lists of words in txt files in order. AnicraftPlayz 2 2,817 Aug-11-2021, 03:45 PM
Last Post: jamesaarr
  Open and read multiple text files and match words kozaizsvemira 3 6,761 Jul-07-2021, 11:27 AM
Last Post: Larz60+
  Why it does not print(file.read()) Rejaul84 1 2,347 Jul-01-2021, 10:37 PM
Last Post: bowlofred

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020