Skip to content
C Codeloom
Python

Strings in Python: Everything a Beginner Needs

A thorough introduction to Python strings — creation, escape sequences, indexing, slicing, the essential methods, f-strings, and why strings are immutable.

·7 min read · By Yash Kesharwani
Beginner 10 min read

What you'll learn

  • Every way to create a Python string
  • Escape sequences and when to use raw strings
  • Indexing, negative indexing, and slicing
  • The string methods you will actually use day to day
  • How to format strings with f-strings
  • Why strings are immutable and what that means in practice

Prerequisites

Strings are the most heavily used type in nearly every program — user input, file paths, URLs, log messages, error text, configuration values, API payloads. Python’s string handling is one of the language’s strengths, and learning it well pays off everywhere else.

Creating strings

A string is text wrapped in quotes. Python accepts three kinds:

single = 'Hello'
double = "Hello"
triple = """Hello"""

Single and double quotes are interchangeable. Most codebases pick one and stick to it (PEP 8 has no preference). The practical reason to mix them is to avoid escaping the same character you used as a delimiter:

quote = "He said \"hi\""    # works but ugly
quote = 'He said "hi"'      # cleaner

Triple-quoted strings can span multiple lines, preserving the newlines verbatim:

paragraph = """This is line one.
This is line two.
This is line three."""

print(paragraph)
# This is line one.
# This is line two.
# This is line three.

Escape sequences

A backslash inside a string starts an escape sequence — a special character represented by two visible characters. The ones you’ll meet most often:

SequenceMeaning
\nNewline
\tTab
\\A literal backslash
\"A literal double quote
\'A literal single quote
print("Line 1\nLine 2")     # two lines of output
print("Name:\tAlice")       # tabbed
print("C:\\Users\\Alice")   # C:\Users\Alice

Raw strings

If you find yourself doubling every backslash — common when writing Windows paths or regular expressions — use a raw string by prefixing the opening quote with r. Escape sequences are not interpreted inside a raw string:

path = r"C:\Users\Alice\Documents"
print(path)   # C:\Users\Alice\Documents

Concatenation and repetition

The + operator joins two strings. The * operator repeats a string a given number of times.

first = "Hello"
second = "World"
print(first + " " + second)   # Hello World
print("-" * 20)               # --------------------

You can only concatenate strings with strings. Adding a number to a string raises a TypeError. Use f-strings (below) or convert explicitly with str():

age = 25
print("Age: " + str(age))   # Age: 25

Length, membership, and iteration

Three operations work on every string:

word = "python"
print(len(word))            # 6
print("y" in word)          # True
print("z" in word)          # False

for letter in word:
    print(letter)           # one letter per line

Indexing

Every character in a string has a numeric index starting from zero on the left and -1 on the right.

word = "Python"
#       0 1 2 3 4 5    (forward)
#      -6-5-4-3-2-1    (backward)

print(word[0])     # P
print(word[5])     # n
print(word[-1])    # n   — last character
print(word[-2])    # o   — second from end

An index outside the valid range raises IndexError.

Slicing

A slice extracts a section of a string. The syntax is s[start:stop:step]. start is inclusive, stop is exclusive, and step defaults to 1.

word = "Python"
print(word[0:3])     # Pyt   — characters 0, 1, 2
print(word[2:5])     # tho
print(word[:3])      # Pyt   — start defaults to 0
print(word[3:])      # hon   — stop defaults to len(word)
print(word[:])       # Python — full copy

print(word[::2])     # Pto   — every second character
print(word[::-1])    # nohtyP — reverse

Slicing is one of Python’s most powerful features and you will use it constantly.

Try it yourself. Given the string s = "programming":

  1. Extract "gram" using slicing.
  2. Extract the last three characters using a negative slice.
  3. Reverse the string.

Essential string methods

A method is a function attached to a value, called with a dot. Strings have many; these are the ones you will use weekly.

Case methods

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

Trimming whitespace

messy = "   hello   "
print(messy.strip())     # "hello"
print(messy.lstrip())    # "hello   "
print(messy.rstrip())    # "   hello"

strip() removes leading and trailing whitespace by default and is invaluable when processing user input or data from files.

Searching and counting

sentence = "the quick brown fox"
print(sentence.find("brown"))    # 10  — index, or -1 if not found
print(sentence.index("brown"))   # 10  — same, but raises if missing
print(sentence.count("o"))       # 2
print(sentence.startswith("the"))   # True
print(sentence.endswith("fox"))     # True

Replacing

text = "I love Java"
print(text.replace("Java", "Python"))   # I love Python

replace() returns a new string — it does not modify the original. (Remember: strings are immutable.)

Splitting and joining

csv = "apple,banana,cherry"
fruits = csv.split(",")
print(fruits)    # ['apple', 'banana', 'cherry']

joined = "-".join(fruits)
print(joined)    # apple-banana-cherry

split and join are inverses of each other, and together they are how virtually every text-processing program converts between strings and lists.

f-strings

By far the most readable way to insert variables into strings is the f-string, introduced in Python 3.6. Add an f before the opening quote and use {} to embed expressions:

name = "Alice"
age = 30
print(f"{name} is {age} years old.")
# Alice is 30 years old.

The expression inside {} can be anything — variables, arithmetic, method calls, conditional expressions:

print(f"In ten years, {name} will be {age + 10}.")
print(f"Name in upper case: {name.upper()}.")

f-strings also support a format specifier after a colon, the same one we saw for numbers:

price = 1234.5678
print(f"Total: ${price:,.2f}")    # Total: $1,234.57

For values you want to debug, the = shortcut prints both the expression and its value — extremely useful while developing:

score = 7
print(f"{score=}")    # score=7

Older code may use .format() or the % operator. They still work, but f-strings should be your default in new code.

Strings are immutable

Strings cannot be changed in place. Any operation that appears to modify a string actually creates a new one:

word = "hello"
word[0] = "H"          # TypeError: 'str' object does not support item assignment

# Correct: reassign
word = "H" + word[1:]
print(word)            # Hello

This has two practical consequences:

  1. Methods like .upper() or .replace() return a new string. You must capture the return value:

    text = "hello"
    text.upper()           # this throws the new string away
    text = text.upper()    # this saves it
  2. Building a string by concatenation in a loop is slow for long strings, because each += allocates a brand-new string. The idiomatic alternative is to build a list and join at the end:

    parts = []
    for word in ["a", "b", "c", "d"]:
        parts.append(word)
    result = " ".join(parts)

Try it yourself. Take the string " Python is awesome " and chain methods to:

  1. Trim leading and trailing whitespace
  2. Convert it to lowercase
  3. Replace "awesome" with "amazing"

You should end up with "python is amazing".

Recap

You now know:

  • Strings can use single, double, or triple quotes, with raw strings for paths and regex
  • Escape sequences handle special characters; backslash escapes them
  • len, in, indexing, and slicing work on every string
  • Essential methods cover case, trimming, searching, replacing, splitting, and joining
  • f-strings are the modern way to embed variables in text
  • Strings are immutable — methods return new strings rather than modifying in place

Next steps

The next post explores lists — Python’s most-used collection type. We’ll cover creation, indexing, slicing, every important method, and the patterns you will use in nearly every program you write.

→ Next: Python Lists: Create, Slice, Mutate, Iterate

Questions or feedback? Email codeloomdevv@gmail.com.