Python Text Processing
Text processing turns messy text into tidy text with string tools. The tools split, clean, count, and rejoin the pieces.
Cut at the commas
split(",") cuts a line of data into a list of pieces.
data = "red,green,blue"
parts = data.split(",")
print(parts)
print(parts[0])Clean each piece
Each piece may carry stray spaces. strip() cleans one piece at a time.
data = " Ada , Bob "
parts = data.split(",")
first = parts[0].strip()
second = parts[1].strip()
print(first)
print(second)Count the words
split() with nothing in the brackets cuts a sentence at its spaces. len() then counts the words.
sentence = "Python is fun to learn"
words = sentence.split()
print(words)
print(len(words))Find and report
find() reports the position of a piece. A result of -1 reports that the piece is missing.
text = "Order 42 is ready"
print(text.find("42"))
print(text.find("shipped"))Rejoin the pieces
join() glues cleaned pieces back into one tidy line.
first = "Ada"
second = "Bob"
names = ", ".join([first, second])
print(names)Example
data = " Ada, Bob ,Cy "
parts = data.split(",")
first = parts[0].strip()
second = parts[1].strip()
third = parts[2].strip()
print("1. " + first)
print("2. " + second)
print("3. " + third)Key points
- Use split(",") to cut comma-separated text into pieces
- Text processing chains small string tools into one tidy result.
- Use strip() on each piece to remove stray spaces
- Use split() with len() to count the words in a sentence
- Use find() to report where a piece sits, or that it is missing
- split(",") keeps empty pieces instead.
In this example, data holds one messy line of names. split(",") cuts it into three pieces at the commas. strip() then cleans the stray spaces from each piece, one piece at a time. The three prints put a number and a dot before each tidy name.
Note
split() with nothing in the brackets cuts on any run of spaces and drops empty pieces.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
What does "a,b,c".split(",") give?