0
def my_startswith(s1, s2):
    if s1[0] == s2[0]:
        return True
    elif s1[0] != s2[0]:
        return False
    elif s2 == '':
        return True
    elif s1 == '' and s2 == '':
        return True 

Iam having trouble with the third and fourth elif. Third elif: i need to say that if s1 is a string and s2 is an empty string -> true,
the fourth elif: i need to say that s1 and s2 are empty strings -> true. When I run it, it only reads the first if when i test for situations that belong to the third and fourth elif. Any help s appreciated, thank you.

2
Contributors
3
Replies
59
Views
3 Years
Discussion Span
Last Post by Gribouillis
Featured Replies
  • You cannot use `s[0]` on en empty string, as `s[0]` returns the first char in the string: write the empty strings tests first. Read More

0

In a sequence if...elif...elif...elif, only the first true alternative is executed. Use a print to see what happens:

def my_startswith(s1, s2):
    print((s1[0] == s2[0], s1[0] != s2[0],
            s2 == '', s1 == '' and s2 == ''))
    if s1[0] == s2[0]:
        return True
    elif s1[0] != s2[0]:
        return False
    elif s2 == '':
        return True
    elif s1 == '' and s2 == '':
        return True 

Edited by Gribouillis

0

I get indexerror: string index out of range, are you saying I shouldn't use if, elif, and so on. Because i thought if s1 has a string and s2 is empty the first 2 (if,elif) would be false and the third elif would be true(i also get the same error when i run the original code)

1

You cannot use s[0] on en empty string, as s[0] returns the first char in the string: write the empty strings tests first.

Edited by Gribouillis

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.