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.....
Asked
Active
Viewed 3,942 times
0
-
2`user_input.endswith('S')` or `user_input[-1:] == 'S'` – falsetru Aug 11 '13 at 03:33
-
3Please edit your question to include how you are gathering users input. Are you using raw_input() ? – Bryan Aug 11 '13 at 03:34
-
what @falsetru said, or user_input[-1] if the input is a string (it should be) – Aaron Aug 11 '13 at 03:35
3 Answers
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()
-
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