0

我只是想知道如何找出用户输入的最后一个字符是使用 Python 的。我需要知道它是否是S。提前致谢.....

4

3 回答 3

3

您可以使用内置功能str.endswith()

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

或者,您可以使用Python 的切片表示法

if raw_input('Enter a word: ')[-1:] == 's': # Or you can use [-1]
    do_stuff()
于 2013-08-11T03:33:33.823 回答
1

使用str.endswith

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

帮助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.
于 2013-08-11T03:33:42.363 回答
0

字符串可以被视为字符列表,并且要获取列表的最后一项,您可以使用-1,因此在将字符串转换为小写后(以防万一您有大写的 s),您的代码将如下所示:

if (user_input.lower()[-1] == 's'):
    #Do Stuff
于 2013-08-11T03:33:50.630 回答