Python中的len()函数是什么意思

2023-02-01 08:59:37
目录
Python中的len()函数len()函数获取字符串长度函数:len()总结

Python中的len()函数

描述:

    返回对象的长度(项目数)参数可以是序列(例如字符串、字节、元组、列表或范围)或集合(例如字典、集合或冻结集合)。

    语法:

      len(s)

      参数介绍:

        s>

        返回值:

          返回对象的长度

          下面例子展示len()函数使用方法

          a = (1,2,3,4,5,6) #元组
          b = [1,2,3,4] #列表
          c = range(0,11) #range
          d = {'name':'lisi','age':14} #字典
          e = 'helloworld' #字符串
          f = set([1,2,3,4,5]) #集合
          g = frozenset([1,2,3,4,5,8]) #冻结集合
           
          print(len(a))
          print(len(b))
          print(len(c))
          print(len(d))
          print(len(e))
          print(len(f))
          print(len(g))

          输出

          6
          4
          11
          2
          10
          5
          6

          len()函数获取字符串长度

          函数:len()

          作用:返回字符串、列表、字典、元组等长度

          语法:len(str)

          参数:

            str:要计算的字符串、列表、字典、元组等返回值:字符串、列表、字典、元组等元素的长度

            实例

              计算字符串的长度:
              >>> s = "hello good boy doiido"
              >>> len(s)
              21
                计算列表的元素个数:
                >>> l = ['h','e','l','l','o']
                >>> len(l)
                5
                  计算字典的总长度(即键值对总数):
                  >>> d = {'num':123,'name':"doiido"}
                  >>> len(d)
                  2
                    计算元组元素个数:
                    >>> t = ('G','o','o','d')
                    >>> len(t)
                    4

                    总结

                    以上为个人经验,希望能给大家一个参考,也希望大家多多支持易采站长站。