Extract Data from Strings in Python: Beginner's Guide

A beginner-friendly helper that splits a comma-separated string into a list, shows word count, and extracts the first and last words using Python's split() and join() methods.

Easy Python 3.9+ Aug 9, 2026 Strings & text 15 views 0 copies

Python code

11 lines
Python 3.9+
text = "python,string,extract,beginner"

words = text.split(",")

print("Full text:", text)
print("Word count:", len(words))
print("First word:", words[0])
print("Last word:", words[-1])

joined = " | ".join(words)
print("Joined with separator:", joined)

Output

stdout
Full text: python,string,extract,beginner
Word count: 4
First word: python
Last word: beginner
Joined with separator: python | string | extract | beginner

How it works

The split() method takes a delimiter (here, a comma) and breaks the string into a list of substrings. The len() function returns the number of items in that list, giving an instant word count. Indexing with words[0] and words[-1] grabs the first and last elements — Python's negative indexing starts from the end. The join() method is called on the separator string and accepts the list, producing a single formatted string. Together these cover the core string-to-list and list-to-string patterns used everywhere in Python data work.

Common mistakes

  • Calling `split()` without an argument, which splits on whitespace instead of commas
  • Using `words[1]` expecting the first word instead of `words[0]`
  • Forgetting that `split()` returns a list, so you cannot call `.upper()` directly on the result
  • Passing the list as the first argument to `join()` instead of calling `join()` on the separator

Variations

  1. Use `text.split(', ')` when the string has spaces after commas
  2. Extract only the last word with `words[-1]` or use `text.rsplit(',', 1)[-1]`

Real-world use cases

  • Parsing CSV-style configuration strings from environment variables into lists for app settings.
  • Splitting a user-provided list of email addresses or tags into individual items for form processing.
  • Joining a list of database column names into a display string for logging or reporting.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Strings & text

Related tutorials and quizzes for this topic.