Skip to main content
 首页 » 编程设计

python之没有 len 函数的字符串长度

2025年05月04日26jiqing9006

谁能告诉我如何在不使用 len() 函数或任何字符串方法的情况下获取字符串的长度。请任何人告诉我,因为我正在疯狂地敲我的头寻找答案。
谢谢。

请您参考如下方法:

>>> sum(map(lambda x:1, "hello world")) 
11 
 
>>> sum(1 for x in "foobar") 
6 
 
>>> from itertools import count 
>>> zip(count(1), "baz")[-1][0] 
3 

一个“绕口令”

>>> sum(not out not in out for out in "shake it all about") 
18 

一些递归的解决方案

>>> def get_string_length(s): 
...     return 1 + get_string_length(s[1:]) if s else 0 
...  
>>> get_string_length("hello world") 
11 
>>> def get_string_length_gen(s): 
...     yield 1 + next(get_string_length_gen(s[1:])) if s else 0 
...  
>>> next(get_string_length_gen("hello world")) 
11 
>>>