voidex/20-29 Areas/20 Programming/20.01 Python/len().md

39 lines
988 B
Markdown

---
title: len()
tags:
- python
- functions
- strings
aliases:
- len
- length
- string-length
---
> [!note] Concept
> The `len()` function returns the number of characters in a string (including spaces and punctuation).
>
> > [!example] Example
> > ```python
> > len('hello') # 5
> > len('My very energetic monster just scarfed nachos.') # 46
> > len('') # 0
> >
> > name = "Alice"
> > print("The length of your name is:")
> > print(len(name)) # 5
> > ```
>
> > [!important] Best Practices
> > - `len()` always returns an integer.
> > - You must convert the result to a string when concatenating:
> > ```python
> > print("I am " + str(29) + " years old.") # OK
> > ```
> > - Mixing integers and strings with `+` will raise a `TypeError`.
>
> > [!info] Related Notes
> > [[functions]]
> > [[typeConversions]]
> > [[expressions]]
> > [[pythonSyntaxOverview]]