liveBook · Manning

Concatenation

As explained in The Quick Python Book, Fourth Edition

Concatenation is the operation of joining ordered sequences end to end to form a single sequence.

String concatenation combines strings into one string. In Python, the + operator is a simple, common way to do it. section 6.2

Each use of + creates a new string, so repeatedly concatenating many pieces can be inefficient. Use join to assemble a list of strings into one string, with a chosen separator between elements. section 6.4.1

Combine two strings

"Hello " + "World" produces "Hello World". section 6.2

import string                                            #1
punct = str.maketrans("",  "", string.punctuation)       #2
 
with open("moby_01.txt") as infile: 
    with open("moby_01_clean.txt", "w") as outfile:
        for line in infile:
            # make all one case
            cleaned_line = line.lower()
        
            # remove punctuation
            cleaned_line = cleaned_line.translate(punct) #3
        
            # split into words
            words = cleaned_line.split()
            cleaned_words = "\n".join(words)             #4
            # write all words for line
            outfile.write(cleaned_words)

This file-cleaning example joins each line’s words with newline characters instead of concatenating them one at a time. section 6.10.2

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Explains + and its repeated new-string cost, then contrasts join without descending into lower-level implementation details.
Examples
Demonstrates joining “Hello ” and “World” and replacing newline concatenation in a text-file cleaning task.
What you can do after
Apply + for simple string combinations and use join to assemble many strings efficiently.
How it connects
Links concatenation to the string methods split and join, especially for processing delimited text.

Also explained in

Compare how 10 books explain concatenation →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.