-3

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"
user2278906
  • 121
  • 5
  • 7
  • 12
  • Why I downvoted this question: http://meta.stackexchange.com/a/149138/133242 – Matt Ball Apr 15 '13 at 05:03
  • Why I downvoted the question: because you did not show the most basic effort for resolving the problem yourself. –  Apr 15 '13 at 05:16
  • 2
    does `Yesterday` count? – georg Apr 15 '13 at 09:01
  • Does this answer your question? [Checking whether a string starts with XXXX](https://stackoverflow.com/questions/8802860/checking-whether-a-string-starts-with-xxxx) – AMC Feb 21 '20 at 18:00

6 Answers6

13

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"
Artsiom Rudzenka
  • 27,895
  • 4
  • 34
  • 52
  • do you know how to check if a string does not start with "Yes"? – user2278906 Apr 15 '13 at 05:13
  • @user2278906 please please read this: http://docs.python.org/2/tutorial/introduction.html – jamylak Apr 15 '13 at 05:23
  • @user2278906 check the updated answer, the idea is that startswith itself returns you a boolean value on whether strings starting(True) with the specified parameter or not(False), So all that you need is to put 'not' and this will revert logic – Artsiom Rudzenka Apr 15 '13 at 05:57
6

Possibly more flexible is good

if s.lower().startswith("yes"):
    return "Yes"
elif s.lower().startswith("no"):
    return "No"
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
0

Have you tried:

yourString.startsWith("Yes")
0

All you need is

String.startswith("yes")

if the string doesn't start with yes it will return false and if it does, true.

Jake Schievink
  • 409
  • 4
  • 16
0

name = "Yes? test"

if name.index('Yes') == 0:

print 'String find!!'
Hemant
  • 99
  • 2
0

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