Python len() 函数:如何查找字符串长度
Python len() 函数
len() 是 Python 的内置函数。您可以使用 len() 来获取给定字符串、数组、列表、元组、字典等的长度。您可以使用 len 函数来优化程序的性能。存储在对象中的元素数量永远不会被计算,因此 len 有助于提供元素数量。
语法
len(value)
参数
值:您想要获取长度的给定值。
返回值
它将返回一个整数值,即给定字符串、数组、列表或集合的长度。
各种返回类型
字符串
它返回字符串中的字符数,包括标点符号、空格和所有类型的特殊字符。但是,在使用 Null 变量的 len 时要非常小心。
空
空是第二个返回值,它有零个字符,但它始终是 None。
集合
len 内置函数返回集合中的元素数量。
TypeError
Len 函数取决于传递给它的变量的类型。非类型没有任何内置支持。
字典
对于字典,每个键值对被算作一个单位。但是,值和键不是独立的。
示例 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:如何在 Python 中查找列表的长度?
# 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:如何在 Python 中查找元组的长度
# 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:如何在 Python 中查找字典的长度?
# 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:如何在 Python 中查找数组的长度
# 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() 来获取给定字符串、数组、列表、元组、字典等的长度。
- 值:您想要获取长度的给定值。
- 返回值:返回一个整数值,即给定字符串、数组、列表或集合的长度。