Python Basics — Strings Basics

4 minute read

Strings Basics

A string is a sequence of characters. Strings are one of the most commonly used data types in Python — they represent text data like names, messages, file paths, and more.

Creating Strings

Python lets you create strings with single quotes, double quotes, or triple quotes:

# Single quotes
name = 'Alice'

# Double quotes
greeting = "Hello, World!"

# Triple quotes (multi-line strings)
paragraph = """This is a
multi-line string that
spans several lines."""

# Triple single quotes work too
another = '''Also a
multi-line string.'''

print(name)       # Alice
print(greeting)   # Hello, World!
print(paragraph)
# This is a
# multi-line string that
# spans several lines.

When to use which:

Type Best For
Single quotes '...' Short strings, no apostrophes
Double quotes "..." Strings with apostrophes: "it's"
Triple quotes """...""" Multi-line strings, docstrings

String Indexing

Every character in a string has a position called an index. Python uses zero-based indexing — the first character is at position 0.

word = "Python"
#       P  y  t  h  o  n
#       0  1  2  3  4  5   ← positive index
#      -6 -5 -4 -3 -2 -1   ← negative index

print(word[0])    # P (first character)
print(word[1])    # y
print(word[5])    # n (last character)
print(word[-1])   # n (last character using negative index)
print(word[-2])   # o (second to last)

Negative indexing counts from the end: -1 is the last character, -2 is second to last, and so on.

String Length

Use len() to get the number of characters in a string:

message = "Hello"
print(len(message))  # 5

empty = ""
print(len(empty))    # 0

String Concatenation

Join strings together with the + operator:

first = "Hello"
second = "World"
result = first + " " + second
print(result)  # Hello World

Note: You can only concatenate strings with strings. Adding a string and a number causes a TypeError:

# ❌ This causes an error
# print("Age: " + 25)  # TypeError

# ✅ Convert the number to a string first
print("Age: " + str(25))  # Age: 25

# ✅ Or use an f-string (preferred)
print(f"Age: {25}")  # Age: 25

String Repetition

Use * to repeat a string:

print("Ha" * 3)     # HaHaHa
print("-" * 40)      # ----------------------------------------

Escape Characters

Escape characters start with a backslash (\) and represent special characters:

Escape Meaning Example Output
\n Newline "Line1\nLine2" Line1
Line2
\t Tab "Col1\tCol2" Col1 Col2
\\ Backslash "C:\\Users" C:\Users
\' Single quote 'It\'s' It’s
\" Double quote "Say \"Hi\"" Say “Hi”
# Newline
print("Hello\nWorld")
# Hello
# World

# Tab
print("Name\tAge")
print("Alice\t25")
# Name    Age
# Alice   25

# Backslash in file paths
path = "C:\\Users\\Alice\\Documents"
print(path)  # C:\Users\Alice\Documents

Raw Strings

Prefix a string with r to create a raw string where backslashes are treated literally (no escape processing):

# Regular string — \n is a newline
print("Hello\nWorld")
# Hello
# World

# Raw string — \n is literal text
print(r"Hello\nWorld")
# Hello\nWorld

# Useful for file paths and regex patterns
path = r"C:\Users\Alice\new_folder"
print(path)  # C:\Users\Alice\new_folder

String Immutability

Strings in Python are immutable — once created, you cannot change individual characters:

word = "Hello"
# word[0] = "J"  # ❌ TypeError: 'str' object does not support item assignment

# ✅ Create a new string instead
word = "J" + word[1:]
print(word)  # Jello

Basic String Methods

Here are some commonly used string methods. We’ll cover all methods in detail in the Strings chapter.

text = "  Hello, World!  "

# Case methods
print(text.upper())       # "  HELLO, WORLD!  "
print(text.lower())       # "  hello, world!  "
print(text.title())       # "  Hello, World!  "

# Whitespace removal
print(text.strip())       # "Hello, World!"
print(text.lstrip())      # "Hello, World!  "
print(text.rstrip())      # "  Hello, World!"

# Search
print(text.find("World")) # 9
print("Hello" in text)    # True

# Replace
print(text.replace("World", "Python"))
# "  Hello, Python!  "

String Methods Reference (Preview)

Method Description Example
upper() Convert to uppercase "hi".upper() → "HI"
lower() Convert to lowercase "HI".lower() → "hi"
strip() Remove leading/trailing whitespace " hi ".strip() → "hi"
split() Split into a list "a,b,c".split(",") → ["a","b","c"]
join() Join a list into a string ",".join(["a","b"]) → "a,b"
replace() Replace substring "hi".replace("hi","bye") → "bye"
find() Find position of substring "hello".find("ll") → 2
count() Count occurrences "hello".count("l") → 2
startswith() Check prefix "hello".startswith("he") → True
endswith() Check suffix "hello".endswith("lo") → True

Common Mistakes

Mistake Example Fix
Index out of range "Hi"[5] → IndexError Check len() first
Concatenating non-strings "Age: " + 25 → TypeError Use str(25) or f-strings
Modifying in place s[0] = "X" → TypeError Create a new string
Forgetting zero-indexing First char at index 1 First char is at index 0

Summary

  • Strings are created with single, double, or triple quotes
  • Indexing starts at 0 — use negative indices to count from the end
  • Strings are immutable — you can’t change individual characters
  • Use + to concatenate, * to repeat, and len() for length
  • Escape characters (\n, \t, \\) insert special characters
  • Raw strings (r"...") ignore escape sequences
  • String methods like upper(), lower(), strip(), and replace() return new strings

Next up: Booleans & None →

Updated: