Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

pythonlen函数具体用法

作者:热血震荡   发布日期:2026-06-28   浏览:64

# 示例代码:使用 len() 函数获取字符串、列表、元组等的长度

# 获取字符串的长度
string = "Hello, Python!"
length_of_string = len(string)
print(f"字符串 '{string}' 的长度是: {length_of_string}")  # 输出: 字符串 'Hello, Python!' 的长度是: 13

# 获取列表的长度
my_list = [1, 2, 3, 4, 5]
length_of_list = len(my_list)
print(f"列表 {my_list} 的长度是: {length_of_list}")  # 输出: 列表 [1, 2, 3, 4, 5] 的长度是: 5

# 获取元组的长度
my_tuple = ('apple', 'banana', 'cherry')
length_of_tuple = len(my_tuple)
print(f"元组 {my_tuple} 的长度是: {length_of_tuple}")  # 输出: 元组 ('apple', 'banana', 'cherry') 的长度是: 3

# 获取字典的长度(返回键的数量)
my_dict = {'a': 1, 'b': 2, 'c': 3}
length_of_dict = len(my_dict)
print(f"字典 {my_dict} 的长度是: {length_of_dict}")  # 输出: 字典 {'a': 1, 'b': 2, 'c': 3} 的长度是: 3

# 获取集合的长度
my_set = {1, 2, 3, 4, 5}
length_of_set = len(my_set)
print(f"集合 {my_set} 的长度是: {length_of_set}")  # 输出: 集合 {1, 2, 3, 4, 5} 的长度是: 5

解释说明:

  • len() 是 Python 内置函数,用于返回对象的长度或元素个数。
  • 它可以作用于多种数据类型,如字符串、列表、元组、字典和集合等。
  • 对于字符串,len() 返回字符的数量。
  • 对于列表、元组和集合,len() 返回元素的数量。
  • 对于字典,len() 返回键的数量。

上一篇:python dict 删除元素

下一篇:python生成excel文件

大家都在看

python 二维码识别

python excel 库

python时间格式

pythoneval函数用法

列表切片操作python

python读取文件路径

python集合中的元素可以是列表

staticmethod在python中有

python 保存json文件

python的assert基本用法

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站