String length without len function

前端 未结 17 1311
逝去的感伤
逝去的感伤 2020-12-10 21:29

Can anyone tell me how can I get the length of a string without using the len() function or any string methods. Please anyone tell me as I\'m tapping my head ma

17条回答
  •  星月不相逢
    2020-12-10 21:48

    Here's a way to do it by counting the number of occurences of the empty string within the string:

    def strlen(s):
        return s.count('') - 1
    

    Since "".count("") returns 1, you have to subtract 1 to get the string's length.

提交回复
热议问题