I want to make a function which checks whether a string starts with "Yes" or "No" but I'm not sure how.
If string begins with "Yes"
return "Yes"
I want to make a function which checks whether a string starts with "Yes" or "No" but I'm not sure how.
If string begins with "Yes"
return "Yes"
Try startswith function:
if myStr.startswith("Yes"):
return "Yes"
elif myStr.startswith("No"):
return "No"
Note that there is also endswith function to check that your string is ending with the text expected.
If you need to check that string is not starts with:
if not myStr.lower().startswith("yes"):
return "Not Yes"
elif not myStr.lower().startswith("no"):
return "Not No"
Possibly more flexible is good
if s.lower().startswith("yes"):
return "Yes"
elif s.lower().startswith("no"):
return "No"
Have you tried:
yourString.startsWith("Yes")
All you need is
String.startswith("yes")
if the string doesn't start with yes it will return false and if it does, true.
This may be the best solution:
def yesOrNo(j):
if j[0].lower() == 'y':
return True
elif j[0].lower() == 'n':
return False
else:
return None
def untilYN():
yn = input('Yes or no: ')
j = yesOrNo(yn)
while j == None:
yn = input('Please insert yes or no again; there may have been an error: ')
j = yesOrNo(yn)
return j
print(untilYN())
For example:
print(untilYN())
>> Yes or no: Maybe
>> Please insert yes or no again; there may have been an error: yeah then
True