Python len() Funkce: Jak zjistit délku řetězce
Python len() Funkce
len() je vestavěná funkce v pythonu. Můžete použít len() k získání délky daného řetězce, pole, seznamu, n-tice, slovníku atd. Funkci len můžete použít k optimalizaci výkonu programu. Počet prvků uložených v objektu se nikdy nepočítá, takže len pomáhá určit počet prvků.
Syntax
len(value)
parametry
Hodnota: daná hodnota, jejíž délku chcete.
Návratová hodnota
Vrátí celočíselnou hodnotu, tj. délku daného řetězce, pole, seznamu nebo kolekcí.
Různé typy návratových hodnot:
Řetězce:
Vrací počet znaků v řetězci, který zahrnuje interpunkci, mezery a všechny typy speciálních znaků. Při používání len proměnné Null byste však měli být velmi opatrní.
Prázdný:
Prázdné je druhé zpětné volání, které má nula znaků, ale vždy je žádné.
Sbírky:
Vestavěná čočka vrací počet prvků v kolekci.
Chyba typu:
Funkce Len závisí na typu proměnné, která je jí předána. Non-Type nemá žádnou vestavěnou podporu.
Slovník:
U slovníku se každý pár počítá jako jedna jednotka. Hodnoty a klíče však nejsou nezávislé.
Příklad 1: Jak zjistit délku daného řetězce?
# testing len() str1 = "Welcome to Guru99 Python Tutorials" print("The length of the string is :", len(str1))
Výstup:
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))
Výstup:
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))
Výstup:
The length of the tuple is 3
Příklad 4: Jak zjistit délku slovníku v 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))
Výstup:
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))
Výstup:
The length of the Array is 4
Shrnutí
- len() je vestavěný funkce v pythonu. Pomocí len() můžete získat délku daného řetězce, pole, seznamu, n-tice, slovníku atd.
- Hodnota: daná hodnota, jejíž délku chcete.
- Návratová hodnota a vrátí celočíselnou hodnotu, tj. délku daného řetězce, pole, seznamu nebo kolekcí.