工業製造
産業用モノのインターネット | 工業材料 | 機器のメンテナンスと修理 | 産業プログラミング |
home  MfgRobots >> 工業製造 >  >> Industrial programming >> Python

Python len()関数:オブジェクトの長さを測る実践ガイド

Pythonでは、len()はオブジェクト内のアイテム数を返す組み込み関数です。文字列、リスト、タプル、辞書、その他のコレクションを扱う際、len()はコストのかかる反復処理なしでサイズを素早く効率的に取得する方法を提供します。

構文

len(value)

パラメータ

value – 長さを測定したいオブジェクト。

戻り値

指定されたオブジェクト内の要素数を表す整数を返します。

文字列

文字列の場合、len()はスペース、句読点、特殊文字を含むすべての文字をカウントします。Noneを渡すとTypeErrorが発生するので注意してください。

コレクション

エッジケース

実例

1. 文字列の長さ

# 例1
str1 = "Welcome to Guru99 Python Tutorials"
print("The length of the string is:", len(str1))
出力: The length of the string is: 35

2. リストの長さ

# 例2
list1 = ["Tim", "Charlie", "Tiffany", "Robert"]
print("The length of the list is", len(list1))
出力: The length of the list is 4

3. タプルの長さ

# 例3
tup = ("Jan", "Feb", "March")
print("The length of the tuple is", len(tup))
出力: The length of the tuple is 3

4. 辞書の長さ

# 例4
dict_obj = {"Tim": 18, "Charlie": 12, "Tiffany": 22, "Robert": 25}
print("The length of the dictionary is", len(dict_obj))
出力: The length of the dictionary is 4

5. 配列の長さ (リスト相当)

# 例5
arr = ["Tim", "Charlie", "Tiffany", "Robert"]
print("The length of the array is", len(arr))
出力: The length of the array is 4

重要なポイント

Python

  1. Python strip()メソッド完全ガイド:実践例付き
  2. Python str.count()マスター:文字と部分文字列のカウント実例集
  3. Python format()文字列を明確な例でマスター
  4. Python len()関数:オブジェクトの長さを測る実践ガイド
  5. Python String.find()メソッド完全ガイド:構文、例、代替手法
  6. Python yieldをマスター:ジェネレータvs return – 実践ガイド
  7. Python collections.Counter:効率的なカウント、更新、演算操作
  8. Java String.length()メソッド:文字列サイズ取得の実例解説
  9. Java String.charAt()完全解説:構文、戻り値、例外、実例
  10. Java String.contains()メソッド:部分文字列チェックの実践例
  11. Java String.endsWith()マスター:文字列サフィックスチェック実例付き