search

Home  >  Q&A  >  body text

一条python的作业题

给定由大写,小写字母和空格组成的字符串,返回最后一个单词的长度。
如果不存在最后一个单词,返回0
注意:
“单词”是指不包含空格符号的字符串
例如:
s = “hello World”, 那么返回的结果是5
格式:
第一行输入字符串s,然后输出s中最后一个单词的长度。
样例1
输入:
Today is a nice day
输出:
3
这是我写的:
nb = raw_input()
arr = nb.split(' ')
print len(arr[-1])
这样明明可以得出结果的,但网站提示不能通过,是不是还有其他办法?能帮我写另外一个看看嘛

怪我咯怪我咯2795 days ago673

reply all(5)I'll reply

  • 黄舟

    黄舟2017-04-17 16:43:38

    try:
        nb = raw_input()
        arr = nb.rstrip().split(' ')
        if len(arr) > 0:
            print len(arr[-1])
        else:
            print 0
    except:
        print 0

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 16:43:38

    Is there a space between the two single quotes in split? 

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-17 16:43:38

    I don’t know what kind of website you are, lz, but your code is fine. Maybe there is something wrong with the input string being read on the website? I hope you can provide the website you mentioned

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 16:43:38

    Uh-huh. . It would be better to change split(' ') to split(). It seems that split(' ') will convert
    as a into
    ['as', '', '', '', 'a', '', '', '']

    while (True):
        sub_str = raw_input().split()
    
        try:
            print len(sub_str[-1])
        except IndexError:
            print 0

    That might be ok

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 16:43:38

    Consider edge cases, i.e. empty strings

    reply
    0
  • Cancelreply