【问题标题】:Get the length of the last word in a string [duplicate]获取字符串中最后一个单词的长度[重复]
【发布时间】:2021-02-15 00:36:50
【问题描述】:

我需要编写一个 Python 程序来只给我字符串中最后一个单词的长度。

但是,如果最后没有单词,它应该返回0。

例如

input = 'Hello World'
output = length of World = 5

input = "Hello World '
Output = 5

input = " "
output = 0

【问题讨论】:

  • 您在这里要求的不是特定问题。是的,标题是,但问题不是。在 Python 中从字符串中删除前导和尾随空格的函数是 strip()。您向我们提出的要求是让我们完成您的作业。

标签: python string


【解决方案1】:

rsplit 按分隔符(空格)计数 (1) 次拆分字符串。 如果什么都没有,rsplit 返回零长度字符串的列表(仅适用于分隔符)。如果没有分隔符,可能会得到空数组。更多内容请关注docs

因此,您不必在按索引访问之前进行检查。

然后返回最后一项的长度。

def last_word_length(string):
    return len(string.rsplit(' ', 1)[-1])

测试:

print(last_word_length('Hello world'))  # 5
print(last_word_length(' '))            # 0
print(last_word_length(''))             # 0
print(last_word_length('a'))            # 1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-07
    • 1970-01-01
    • 2018-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-14
    相关资源
    最近更新 更多