📜  Python字符串长度 | len()

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

Python字符串长度 | len()

Python len()函数返回字符串的长度。

Python len() 语法:

len() 参数:

它接受一个字符串作为参数。

len() 返回值:

它返回一个整数,它是字符串的长度。

Python len() 示例

示例 1:具有元组、列表和字符串的 Len()函数

Python
# Python program to demonstrate the use of
# len() method 
 
# Length of below string is 5
string = "geeks"
print(len(string))
 
# with tuple
tup = (1,2,3)
print(len(tup))
 
# with list
l = [1,2,3,4]
print(len(l))


Python3
print(len(True))


Python3
# Python program to demonstrate the use of
# len() method 
 
dic = {'a':1, 'b': 2}
print(len(dic))
 
s = { 1, 2, 3, 4}
print(len(s))


Python3
class Public:
    def __init__(self, number):
        self.number = number
    def __len__(self):
        return self.number
     
obj = Public(12)
print(len(obj))


输出:

5
3
4

示例 2: Python len() 类型错误

Python3

print(len(True))

输出:

TypeError: object of type 'bool' has no len()

示例 3:带有字典和集合的Python len()

Python3

# Python program to demonstrate the use of
# len() method 
 
dic = {'a':1, 'b': 2}
print(len(dic))
 
s = { 1, 2, 3, 4}
print(len(s))

输出:

2
4

示例 4:带有自定义对象的Python len()

Python3

class Public:
    def __init__(self, number):
        self.number = number
    def __len__(self):
        return self.number
     
obj = Public(12)
print(len(obj))

输出:

12