Python 字符串 len() 方法



Python 字符串len()方法用于获取字符串的长度。字符串是字符的集合,字符串的长度是其中字符(Unicode 值)的数量。

len() 方法确定字符串中包含多少个字符,包括标点符号、空格和所有类型的特殊字符。它不会计算存储在对象中的元素数量,因此此方法有助于提供元素的数量。

例如,字符串“Tutorials Point”包含 15 个字符,包括空格。

语法

以下是 Python 字符串 len() 方法的语法

len(str)

参数

此方法不接受任何参数。

返回值

此方法返回字符串的长度。

示例

在下面的示例中,我们使用 Python 字符串 len() 方法查找给定字符串“this is string example....wow!!!”的长度

str = "this is string example....wow!!!";
print "Length of the string: ", len(str)

以上代码的输出如下

Length of the string:  32

示例

以下是一个创建字符串列表的示例。然后使用 len() 方法返回列表的长度

# finding the length of the list
li = ["Python","Java","CSS","Javascript"]
# Returning the length of the list
print("The length of the given list is:", len(li))

以上代码的输出如下

The length of the given list is: 4

示例

在下面给出的示例中,创建了一个元素数组。然后使用 len() 方法返回数组的大小

# finding the length of the array
array = ["Jyoti","Radhika","Kriti","Suhana","Akriti","Ankita","Nachiket"]
# Returning the length of the list
print("The length of the given array is:", len(array))

执行以上代码后,我们得到以下输出

The length of the given array is: 7

示例

在下面的示例中,创建一个字典并返回字典的长度

# finding the length of the dictionary
dictionary = {'Player': 'Sachin Tendulkar', 'Sports':'Cricket', 'age':48}
res = len(dictionary)
# Returning the length of the list
print("The length of the given array is:", res)

运行以上程序时,会产生以下结果

The length of the given array is: 3
python_strings.htm
广告