voidex/20-29 Areas/20 Programming/20.01 Python/stringConcatenation.md

37 lines
1 KiB
Markdown

---
title: stringConcatenation
tags:
- python
- concatenation
aliases:
- join-strings
- strings +
---
> [!note] String Concatenation
> The `+` operator, when used with two strings, combines them into a single new string — this is called **string concatenation**.
>
> > [!example] Examples
> > ```python
> > 'Alice' + 'Bob' # AliceBob
> > 'Alice' + 42 # TypeError: can only concatenate str (not 'int') to str
> > 'Alice' + str(42) # Alice42
> > 'Alice' * 5 # AliceAliceAliceAliceAlice
> >
> > name = "Al"
> > print("It is good to meet you, " + name) # It is good to meet you, Al
> > ```
>
> > [!important] Best Practices
> > - Ensure both operands are strings before using `+`
> > - Prefer `f-strings` or `format()` for cleaner code when mixing types
> > ```python
> > f"Alice{42}" # Alice42
> > ```
>
> > [!info] Related Notes
> > [[typeConversions]]
> > [[expressions]]
> > [[len()]]
> > [[The print() Function]]
> > [[pythonSyntaxOverview]]