一条python的作业题
怪我咯
怪我咯 2017-04-17 16:41:38
0
5
672

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

怪我咯
怪我咯

走同样的路,发现不同的人生

reply all(5)
黄舟
try:
    nb = raw_input()
    arr = nb.rstrip().split(' ')
    if len(arr) > 0:
        print len(arr[-1])
    else:
        print 0
except:
    print 0
洪涛

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

巴扎黑

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

Ty80

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

洪涛

Consider edge cases, i.e. empty strings

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template