If string ends and starts with "*" in Python

Viewed 91

Is there a simple if statement to battle this problem? The first block is my code so far, the second block is the boolean output I wish would be printed.

if string.startswith("*") and string.endswith("*"):
    return True
else:
    return False



print(string_startend_function('*JohnDoe*'))  # True (This answer my code can achieve)
print(string_startend_function('*'))  # False (This answer my code can't achieve)

I need my code to display False if the startswith * and endswith * are the same singular *, is there anyway to achieve this, with adding a elif statement after the if statement?

3 Answers

Since '*' is the only possible value for string where string.startswith("*") and string.endswith("*") is True and where the function should return False, you can simply add an inequality test to make sure that string is literally not '*':

return string != '*' and string.startswith("*") and string.endswith("*")

You could also use a regular expression like ^\*.*\*$, meaning "start, literal *, more stuff, literal *, end"

>>> import re
>>> re.match(r"^\*.*\*$", "*") is not None
False
>>> re.match(r"^\*.*\*$", "*JohnDoe*") is not None
True
>>> re.match(r"^\*.*\*$", "*invalid") is not None
False

The solution which comes to me is regular expression, BUT:

For short code, how about this code?

return len(s) > 1 and s[0] + s[-1] == "**"

with not using startWith or endWith method :)

Related