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 madly for the answer.
Thank you.
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
Here's a method which isn't using neither
len
nor iteration:To make it work for lists, which don't have
rindex
, use:Here's an O(1) method:
In other words, it doesn't work by counting the characters, so should be just as fast for a 1GB string as it is for a 1 byte string.
It works by looking at the last character and searching from the very end to find that character. Since it's the last character it will always find it at the first place it looks, essentially always returning the index of the last character. The length is just one more than the index of the last character.
It's a weird question so here's a weird answer!
Why you need to avoid the len function is beyond me, but strings are iterables. You should be able to do this:
If string contains new lines