Python Forum
Program: count and find
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Program: count and find
#1
# [ ] find and report (print) number of w's, o's + use of word "code"
work_tip = "Good code is commented code"

# [ ] count times letter "i" appears in code_tip string
# [ ] find and display the index of all the letter i's in code_tip
# Remember: if .find("i") has No Match, -1 is returned
code_tip = "code a conditional decision like you would say it"
print ("code_tip:" , code_tip)

my code:
code_tip = "code a conditional decision like you would say it"
a = code_tip.count("w")
b = code_tip.count("o")
c = code_tip.count("code")
print(a)
print(b)
print(c)
cnt = code_tip.count("i")
print(cnt)
ind = code_tip.find("i")
for i in code_tip:
    if code_tip.find("i"):
        print(ind)
        break
    else:
        print("not found")
print ("code_tip:" , code_tip)
I have a problem with bolded task. Don't know how to print indexes for all six i's. Help is appreciated.
Reply
#2
To get index,
print(code_tip.index('i'))
you can then use slice
see: http://www.pythonforbeginners.com/dictio...on-slicing
Reply
#3
Larz, this code gives output 6. My understanding of the task is that I should find a way to print all indexes, for each 'i'.
By the way, I know about slicing.
Reply
#4
That's why I included:
Quote:you can then use slice
see: http://www.pythonforbeginners.com/dictio...on-slicing
Your prof probably wants you to use slice. Get index, slice at index, get next index, appending results to list.
If allowed, you can also use list comprehension
list_of_i = [i for i, x in enumerate(code_tip) if x == 'i']
>>> code_tip = "code a conditional decision like you would say it"
>>> list_of_i = [i for i, x in enumerate(code_tip) if x == 'i']
>>> list_of_i
[11, 13, 22, 24, 29, 47]
>>>
If you turn this in, better be able to explain what's going on.
I suggest reading up on slices and going about it that way
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Python Program to Find the Factorial of a Number elisahill 2 1,424 Nov-21-2022, 02:25 PM
Last Post: DeaD_EyE
  Help on Creating Program to find the Median and Mode by hand EvanCahill 3 2,921 Jul-19-2018, 06:17 PM
Last Post: woooee
  Count Letters in a Sentence (without using the Count Function) bhill 3 5,168 Jun-19-2018, 02:52 AM
Last Post: bhill

Forum Jump:

User Panel Messages

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