我有一个问题,我必须在不使用任何字符串方法的情况下找到字符串最后一个单词的长度.如果允许使用字符串方法,我就可以根据空间进行拆分,并可以使用最后一个单词.

到目前为止,我的try 如下:

string = "Hello how are you"

lst = list(string)
print(lst)

last_word = ""
for i in reversed(lst):
    if i == ' ':
        break
    elif i != ' ':
        last_word += i

    
print(last_word)    
print(len(last_word))

在最后一句话之后没有空格之前,这个方法很有效.

string = "Hello how are you "string = "Hello how are you "时失败

推荐答案

假设你不在乎标点符号,那么从字符串的后面迭代到:

  1. 查找第一个非空白字符:
  2. 查找上述字符之前的第一个空白字符:

101 Calling 100 on a string is O(1).

# Source: https://github.com/python/cpython/blob/738c19f4c5475da186de03e966bd6648e5ced4c4/Objects/unicodetype_db.h#L6151
UNICODE_WHITESPACE_CHARS = {0x0009, 0x000A, 0x000B, 0x000C, 0x000D, 0x001C,
                            0x001D, 0x001E, 0x001F, 0x0020, 0x0085, 0x00A0,
                            0x1680, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004,
                            0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A,
                            0x2028, 0x2029, 0x202F, 0x205F, 0x3000}


def get_last_non_whitespace_index(sentence: str) -> int:
    sentence_length = len(sentence)
    i = sentence_length - 1
    while i >= 0:
        if ord(sentence[i]) not in UNICODE_WHITESPACE_CHARS:
            return i
        i -= 1
    return -1


def get_last_word_len(sentence: str) -> int:
    last_non_whitespace_index = get_last_non_whitespace_index(sentence)
    if last_non_whitespace_index == -1:
        return 0
    i = last_non_whitespace_index
    while i >= 0:
        if ord(sentence[i]) in UNICODE_WHITESPACE_CHARS:
            break
        i -= 1
    return last_non_whitespace_index - i


def main() -> None:
    print(f'{get_last_word_len("Hello how are you") = }')
    print(f'{get_last_word_len("Hello how are you ") = }')
    print(f'{get_last_word_len("Hello how are you  ") = }')
    print(f'{get_last_word_len("") = }')
    print(f'{get_last_word_len("a   ") = }')  # Whitespace is a tab character.


if __name__ == '__main__':
    main()

Output:

get_last_word_len("Hello how are you") = 3
get_last_word_len("Hello how are you ") = 3
get_last_word_len("Hello how are you  ") = 3
get_last_word_len("") = 0
get_last_word_len("a    ") = 1

Python-3.x相关问答推荐

IPython似乎已安装但无法运行

使用魔方无法从图像中识别单个字符

在Python中从mySQL获取多行

Paramiko SFTPClient get()和put()函数的通过/失败结果?

将字符串转换为python日期时间时出错

将两列的乘积连续添加到一列的累积和中

查找值始终为零的行 pandas

如何在 histplot 中标记核密度估计

如何对具有多个列值的 pandas 数据框进行数据透视/数据透视表

以编程方式映射 uniprot ID 时如何解决 400 客户端错误?

如何在python 3.10中将列表项(字符串类型)转换为模块函数

Python 3 `str.__getitem__` 的计算复杂度是多少?

Await Future 来自 Executor:Future 不能在await表达式中使用

如何使用 asyncio 添加连接超时?

创建集合的 Python 性能比较 - set() 与 {} 文字

在python中,如果一个函数没有return语句,它会返回什么?

对字节进行按位运算

TypeError: write() 参数必须是 str,而不是字节(Python 3 vs Python 2)

异常被忽略是什么类型的消息?

注册 Celery 基于类的任务