Python Funkcja len(): Jak znaleźć długość łańcucha

Python Funkcja len().

len() to wbudowana funkcja w Pythonie. Możesz użyć funkcji len(), aby uzyskać długość danego ciągu, tablicy, listy, krotki, słownika itp. Możesz użyć funkcji len, aby zoptymalizować wydajność programu. Liczba elementów przechowywanych w obiekcie nigdy nie jest obliczana, więc len pomaga określić liczbę elementów.

Składnia

len(value)

parametry

wartość: podana wartość, której długość chcesz mieć.

Wartość zwracana

Zwróci wartość całkowitą, tj. długość podanego ciągu, tablicy, listy lub kolekcji.

Różne typy wartości zwracanych:

Ciągi:

Zwraca liczbę znaków w ciągu, która obejmuje znaki interpunkcyjne, spacje i wszelkiego rodzaju znaki specjalne. Należy jednak zachować szczególną ostrożność podczas używania wartości len zmiennej Null.

Pusty:

Puste to drugie wywołanie zwrotne, które ma zero znaków, ale zawsze ma wartość Brak.

Kolekcje:

Wbudowana funkcja len zwraca liczbę elementów w kolekcji.

Błąd typu:

Funkcja Len zależy od typu przekazanej do niej zmiennej. Non-Type nie ma żadnej wbudowanej obsługi.

Słownik:

W słowniku każda para jest liczona jako jedna jednostka. Jednak wartości i klucze nie są niezależne.

Przykład 1: Jak znaleźć długość podanego ciągu?

# testing len() 
str1 = "Welcome to  Guru99 Python Tutorials"
print("The length of the string  is :", len(str1))

Wyjście:

The length of the string  is : 35

Example 2: How to find the length of the list in python?

# to find the length of the list

list1 = ["Tim","Charlie","Tiffany","Robert"]

print("The length of the list is", len(list1))

Wyjście:

The length of the list is 4

Example 3: How to find the length of a tuple in python

# to find the length of the tuple

Tup = ('Jan','feb','march')

print("The length of the tuple is", len(Tup))

Wyjście:

The length of the tuple is 3

Przykład 4: Jak znaleźć długość słownika w Python?

# to find the length of the Dictionary

Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25}

print("The length of the Dictionary is", len(Dict))

Wyjście:

The length of the Dictionary is 4

Example 5: How to find the length of the array in python

# to find the length of the array

arr1 = ['Tim','Charlie','Tiffany','Robert']

print("The length of the Array is", len(arr1))

Wyjście:

The length of the Array is 4

Podsumowanie

  • len() jest funkcją wbudowaną funkcja w Pythonie. Możesz użyć funkcji len(), aby uzyskać długość danego ciągu, tablicy, listy, krotki, słownika itp.
  • Wartość: podana wartość, której długość chcesz mieć.
  • Wartość zwracana Zwraca wartość całkowitą, tj. długość podanego ciągu, tablicy, listy lub kolekcji.