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









