Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Print all items in a string from first instance of item onwards

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.

like image 734
user5390224 Avatar asked Nov 19 '25 16:11

user5390224


1 Answers

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
like image 161
Steven Rumbalski Avatar answered Nov 21 '25 04:11

Steven Rumbalski