最后一个单词的长度

Python rstrip() 删除 string 字符串末尾的指定字符(默认为空格).

以下实例展示了rstrip()函数的使用方法:

#!/usr/bin/python

str = "     this is string example....wow!!!     ";
print str.rstrip();
str = "88888888this is string example....wow!!!8888888";
print str.rstrip('8');


以上实例输出结果如下:

     this is string example....wow!!!
88888888this is string example....wow!!!


Python split() 通过指定分隔符对字符串进行切片,如果参数 num 有指定值,则分隔 num+1 个子字符串

参数

  • str -- 分隔符,默认为所有的空字符,包括空格、换行( )、制表符( )等。
  • num -- 分割次数。默认为 -1, 即分隔所有。

返回值

返回分割后的字符串列表。

实例

以下实例展示了 split() 函数的使用方法:

实例(Python 2.0+)

#!/usr/bin/python # -*- coding: UTF-8 -*- str = "Line1-abcdef Line2-abc Line4-abcd"; print str.split( ); # 以空格为分隔符,包含 print str.split(' ', 1 ); # 以空格为分隔符,分隔成两个

以上实例输出结果如下:

['Line1-abcdef', 'Line2-abc', 'Line4-abcd']
['Line1-abcdef', '
Line2-abc 
Line4-abcd']

class Solution:
    def lengthOfLastWord(self, s: str) -> int:
        s = s.rstrip(' ')
        if ' ' in s :
            return len(s.split(' ')[-1]) 
        else:
            return len(s)
原文地址:https://www.cnblogs.com/xxupup/p/10738473.html