📜  用Python编写自己的 len()

📅  最后修改于: 2022-05-13 01:55:51.198000             🧑  作者: Mango

用Python编写自己的 len()

len() 方法根据您传递的参数返回列表中元素的数量或字符串的长度。

如何在不使用 len() 的情况下实现:

1. Take input and pass the string/list into
   a function which return its length.
2. Initialize a count variable to 0, this count 
   variable count character in the string.
3. Run a loop till length if the string and increment 
   count by 1.
4. When loop is completed return count.

Python实现:

# Function which return length of string
def findLength(string):
  
    # Initialize count to zero
    count = 0
  
    # Counting character in a string
    for i in string:
        count+= 1
    # Returning count
    return count
  
# Driver code
string = "geeksforgeeks"
print(findLength(string))

输出:

13