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.....
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()
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.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.