liveBook · Manning

Concatenation

As explained in Tiny Python Projects: Learn coding and testing with puzzles and games

Concatenation is the operation of combining values or ordered sequences into a single composite, typically preserving their order.

Concatenation joins strings end to end. In Python, the + operator combines literal text and variables into a new string. section 2.1.5 section 2.5

Join a word into a phrase

word = 'narwhal' message = 'Ahoy, Captain, a ' + word + ' off the larboard bow!' print(message) # Ahoy, Captain, a narwhal off the larboard bow! section 2.1.5

Choose a construction technique according to the shape of the output:

  • Use str.format() with {} placeholders when substituting values by argument order. section 2.1.12
  • Use an f-string to place variables directly inside a string template. section 2.1.12
  • Use str.join() or + when assembling generated text, such as insults built from selected words. section 9.1.5 section 10.3.1
>>> 'Ahoy, Captain, a ' + word + ' off the larboard bow!'
'Ahoy, Captain, a narwhal off the larboard bow!'

Inspect the REPL expression and its resulting concatenated sentence. section 2.1.5

How Tiny Python Projects: Learn coding and testing with puzzles and games covers it

How deep it goes
Defines string concatenation and demonstrates +, str.format(), f-strings, and str.join(), stopping short of non-string sequences.
Examples
Uses a narwhal phrase, an article-sensitive aviso test, generated insults, and random string mutation.
What it assumes
Builds from Python assignment, variables, strings, and REPL interaction while demonstrating each operation directly.
What you can do after
Apply it in Python to construct phrases and generated output with +, str.format(), f-strings, or str.join().
How it connects
Connects concatenation with string formatting, f-strings, str.join(), string slicing, and immutable strings.

Also explained in

Compare how 10 books explain concatenation →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Tiny Python Projects: Learn coding and testing with puzzles and games. The section links point to the parts of the book it draws on.