Strings: Work with Text Like a Pro

Introduction

In this chapter, you will learn how strings work in Python and how to manipulate text effectively. Strings are everywhere in real programs, from user names and messages to file paths and API data. Once you understand strings, you can build much more expressive and practical applications.

Prerequisites

  • Python 3.10+ installed
  • Basic understanding of variables and numbers
  • Ability to run .py files in terminal or IDE

What Is a String

A string is a sequence of characters, such as letters, numbers, symbols, or spaces.

Examples:

  • "Hello"
  • "Python 3.10"
  • "user@example.com"
python
# Store text values in variables
language = "Python"
message = "Hello, world!"
 
# Print strings
print(language)
print(message)

1) Creating Strings

You can create strings with single quotes or double quotes.

python
# String with double quotes
city = "New York"
 
# String with single quotes
country = 'USA'
 
# Print values
print(city)
print(country)

If your text contains an apostrophe, double quotes are often easier:

python
# Apostrophe inside string
note = "I'm learning Python."
print(note)

2) String Concatenation and Repetition

Use + to join strings and * to repeat them.

python
# Join two strings
first_name = "Ada"
last_name = "Lovelace"
full_name = first_name + " " + last_name
print(full_name)
 
# Repeat a string
divider = "-" * 20
print(divider)

Tip

Best Practice

For combining text with variables, prefer f-strings because they are easier to read.

f-strings let you insert variables directly into text.

python
# Store values
user_name = "Tom"
learning_days = 13
 
# Build readable message
msg = f"{user_name} has studied Python for {learning_days} days."
print(msg)

4) Useful String Methods

Python provides many built-in methods for text processing.

Change Case

python
# Original text
title = "python for beginners"
 
# Convert case
print(title.upper())   # PYTHON FOR BEGINNERS
print(title.title())   # Python For Beginners

Remove Extra Spaces

python
# Text with extra spaces
raw_name = "   Alice   "
 
# Remove spaces on both sides
clean_name = raw_name.strip()
print(clean_name)

Replace Content

python
# Original sentence
sentence = "I like Java."
 
# Replace a word
new_sentence = sentence.replace("Java", "Python")
print(new_sentence)

Split and Join

python
# CSV-like text
tags_text = "python,strings,basics"
 
# Split into list
tags = tags_text.split(",")
print(tags)
 
# Join back to text
joined = " | ".join(tags)
print(joined)

5) String Indexing and Slicing

You can read parts of a string by position.

python
# Sample text
word = "Python"
 
# Indexing
print(word[0])   # P
print(word[-1])  # n
 
# Slicing
print(word[0:3])  # Pyt
print(word[3:])   # hon

Warning

Index starts at 0, not 1.
Accessing an out-of-range index causes IndexError.

6) Real Mini Example: Username Formatter

This mini tool cleans user input and creates a display name.

python
# Ask user to input first name
first = input("Enter your first name: ").strip()
 
# Ask user to input last name
last = input("Enter your last name: ").strip()
 
# Build full display name in title case
display_name = f"{first} {last}".title()
 
# Create account ID in lowercase
account_id = f"{first}.{last}".lower()
 
# Print final outputs
print(f"Display Name: {display_name}")
print(f"Account ID: {account_id}")

This pattern appears in signup flows, profile setup, and data cleanup tasks.

Surprise Practice Challenge

Build a tiny "Secret Message Styler" script:

  1. Ask user for a sentence
  2. Print:
    • original sentence
    • all uppercase version
    • reversed version
    • word count
  3. Add a decorative border line based on sentence length

Reference implementation:

python
# Ask user for a message
text = input("Type your message: ").strip()
 
# Build transformed versions
upper_text = text.upper()
reversed_text = text[::-1]
word_count = len(text.split())
 
# Build dynamic border
border = "*" * (len(text) + 8)
 
# Print final styled output
print(border)
print(f"* {text} *")
print(border)
print(f"UPPER: {upper_text}")
print(f"REVERSED: {reversed_text}")
print(f"WORDS: {word_count}")

This exercise feels fun, but it also trains core skills used in real text-processing tools.

Common Beginner Mistakes

Mistake 1: Mixing String and Number Without Conversion

"Age: " + 18 will fail. Convert number first: str(18) or use f-strings.

Mistake 2: Forgetting .strip() for User Input

Leading and trailing spaces can cause bugs in comparisons and formatting.

Mistake 3: Assuming String Methods Modify Original Value

Strings are immutable. Methods like .replace() return a new string.

FAQ

Are strings mutable in Python?

No. Strings are immutable, so operations create new strings instead of changing the original one in place.

Should I use + or f-strings for combining text?

Use f-strings in most cases. They are cleaner and easier to maintain.

How do I reverse a string quickly?

Use slicing with a step of -1: text[::-1].

Why does indexing start at 0?

It is a common design choice in many programming languages and aligns with offset-based memory concepts.