I want to print all items in a sequence starting with the first instance of a particular item. To do this I cannot use find or index. I am specifically being asked to use some combination of 'for' statement, linenum(position of an item in the string), length(length of a string) and count(how many times a particular character appears in a string).
So Far I have -
def PrintFrom(c,s):
count = 0
for item in s:
if item == c:
count +=1
if count > 0:
print (item)
What I'm looking for is this:
PrintFrom("x","abcxdef")
->x
->d
->e
->f
If anybody could help me out I would be beyond grateful. Thank you.
You've got it almost exactly right. Indent your second if-statement to the same level as your first if-statement and your code works. Currently the second if-statement is only encountered after the for-loop has ended, which means it is too late to print the items as they are encountered.
def PrintFrom(c,s):
count = 0
for item in s:
if item == c:
count +=1
if count > 0: # indented to be inside of for-loop
print (item)
Run with modifications:
>>> PrintFrom("x","abcxdef")
x
d
e
f
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With