Python len() 函数:如何查找字符串的长度

什么是 Python len() 函数?
此 len() 该函数是内置函数 Python您可以使用 `len()` 函数获取给定字符串、数组、列表、元组、字典和其他对象的长度。由于元素数量存储在对象中,而不是每次都重新计算,因此 `len()` 可以帮助您快速检查对象大小并优化程序性能。
语法 Python len() 函数
此 Python len() 函数使用以下语法:
len(value)
参数
值: 给定一个对象(例如字符串、列表、元组、字典或集合),你要测量它的长度。
回报值
len() 返回一个整数,即字符串中的字符数或数组、列表或集合中的元素数。返回值的具体含义取决于传递给它的对象类型:
- 字串: len() 返回字符串中的字符数,包括标点符号、空格和各种特殊字符。
- 空: 空字符串或空集合返回 0,因为它不包含任何元素。
- 类别: 内置函数 len() 返回集合中存储的元素数量。
- TypeError: len() 函数的长度取决于传递给它的对象的类型。如果传递一个没有长度的值(例如整数),则会引发 TypeError 异常。
- 字典: 对于字典而言,每个键值对都算作一个单位,因此 len() 返回键的数量。
例如 Python len() 函数
以下示例展示了如何使用 len() 函数查找不同长度的字符串。 Python 对象,包括字符串、列表、元组、字典和数组。
例1:如何找到字符串的长度
# testing len()
str1 = "Welcome to Guru99 Python Tutorials"
print("The length of the string is :", len(str1))
输出:
The length of the string is : 35
示例 2:如何查找列表的长度
# to find the length of the list
list1 = ["Tim","Charlie","Tiffany","Robert"]
print("The length of the list is", len(list1))
输出:
The length of the list is 4
例 3:如何查找元组的长度
# to find the length of the tuple
Tup = ('Jan','feb','march')
print("The length of the tuple is", len(Tup))
输出:
The length of the tuple is 3
例 4:如何查找字典的长度
# to find the length of the Dictionary
Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25}
print("The length of the Dictionary is", len(Dict))
输出:
The length of the Dictionary is 4
例 5:如何查找数组的长度
# to find the length of the array
arr1 = ['Tim','Charlie','Tiffany','Robert']
print("The length of the Array is", len(arr1))
输出:
The length of the Array is 4
如何在不使用 len() 函数的情况下查找字符串的长度 Python
`len()` 函数是测量字符串长度最快、最易读的方法,但你也可以手动计算字符数。这是常见的编程面试题,所有方法都只是简单地遍历字符串并递增计数器。
最常用的方法是使用 for 循环:
# length of a string without len()
mystr = "Guru99"
count = 0
for char in mystr:
count += 1
print("The length is", count)
输出:
The length is 6
更简洁的方法是使用 sum() 函数和一个生成器表达式,字符串中的每个字符都加 1:
mystr = "Guru99"
length = sum(1 for char in mystr)
print("The length is", length)
输出:
The length is 6
除了使用 len() 函数之外,还有其他方法可以计算字符数:
- 一个 while 循环,不断切片字符串直到字符串为空,每次循环都递增一个计数器。
- enumerate() 函数, tracks 是迭代过程中每个字符的索引。
- 一个递归函数,返回 1 加上剩余子字符串的长度。
这些手动方法比内置的 `len()` 函数慢,因此建议仅用于学习或面试练习。在日常代码中,`len()` 仍然是最快、最清晰的选择。
怎么样? Python len() 函数内部是如何工作的?
理解 len() 函数的工作原理就能解释为什么它速度这么快。当你对一个对象调用 len() 函数时, Python 它不会逐个扫描每个元素。相反,它会调用对象的特殊方法 __len__(),这意味着表达式 len(x) 等价于 x.__len__()。
内置容器(例如字符串、列表、元组、字典和集合)会将自身大小作为属性存储。每次添加或删除元素时, Python 更新已存储的计数。调用 len() 函数时,它只是读取预先存储的值并返回它。
由于长度已知,len() 函数的时间复杂度为常数,记为 O(1)。无论对象包含五个元素还是五百万个元素,耗时都相同。您还可以通过定义一个返回整数的 __len__() 方法,为自己的类添加 len() 支持:
class Team:
def __len__(self):
return 11
squad = Team()
print(len(squad))
输出:
11
这种设计使得 len() 在每个内置类型以及任何实现了 __len__() 方法的自定义对象中都能表现一致。
“ 学习更多关于 Python 字符串方法
