0

I was just wondering how I could find out what the last character of the user input was using Python. I need to know whether it was an S or not. Thanks in advance.....

Tom
  • 145
  • 2
  • 6

3 Answers3

3

You can use the built-in function str.endswith():

if raw_input('Enter a word: ').endswith('s'):
    do_stuff()

Or, you can use Python's Slice Notation:

if raw_input('Enter a word: ')[-1:] == 's': # Or you can use [-1]
    do_stuff()
Community
  • 1
  • 1
TerryA
  • 58,805
  • 11
  • 114
  • 143
  • 1
    @user2357112: using a slice prevents an IndexError in case of an empty string. – DSM Aug 11 '13 at 03:38
1

Use str.endswith:

>>> "fooS".endswith('S')
True
>>> "foob".endswith('S')
False

help on str.endswith:

>>> print str.endswith.__doc__
S.endswith(suffix[, start[, end]]) -> bool

Return True if S ends with the specified suffix, False otherwise.
With optional start, test S beginning at that position.
With optional end, stop comparing S at that position.
suffix can also be a tuple of strings to try.
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
0

Strings can be treated like lists of characters, and to get the last item of a list you can use -1, so after you convert the string to lowercase (just in case you have an uppercase s), your code will look like:

if (user_input.lower()[-1] == 's'):
    #Do Stuff
scohe001
  • 15,110
  • 2
  • 31
  • 51