☰

Python Strings Tutorials with Examples

Python Strings Tutorial for Beginners With Examples

Every program works with text. A login form reads a name, a report prints a title, a web scraper pulls headlines from a page, and a chatbot reads what you type. In Python, all of that text lives in one data type: the string. You will use strings in almost every program you ever write, so it pays to learn them properly.

A string is a sequence of characters, such as letters, digits, spaces and symbols, written inside quotes. Python gives you a rich set of tools for strings: you can join them, cut pieces out, search them, change their case, clean them and fill them with values. One rule surprises every beginner: a string cannot be changed after it is created. We will see what that means and how to work with it.

In this tutorial, we start with how to write strings and use quotes, then cover multiline strings, joining strings, indexing and slicing. We go through the most useful string methods, with every example run and its real output shown, including f strings, join and the difference between find and index. We end with common mistakes and the full program. The outputs on this page come from a real run on Python 3.13.

What is a String in Python?

A string is an ordered sequence of characters. You create one by putting text inside quotes. Each character has a position, called an index, counted from 0 at the left. You can also count from the right with negative numbers, where minus 1 is the last character.

  • Ordered. The characters stay in the order you wrote them.
  • Indexed. You can reach any character by its position.
  • Immutable. Once created, a string cannot be changed. Any change makes a new string.

String Literals in Python

A string literal is text written directly in your code. Python accepts single quotes, double quotes and triple quotes. The first three lines below print the same word:

python
print('Python')
print("Python")
print('''Python''')
output
Python
Python
Python

Why have two kinds of quote? It lets you put one inside the other without trouble. For example, “It’s easy” works because the apostrophe is safe inside double quotes.

How to Assign a String to a Variable?

Give the string a name with an equals sign, then use the name.

python
text = "python"
print(text)
output
python

Multiline Strings in Python

Triple quotes, either three single or three double, let a string run across several lines. Line breaks inside become part of the string.

python
poem = """Welcome to
the python
world"""
print(poem)
output
Welcome to
the python
world

Concatenation of Python Strings

Concatenation means joining strings with a plus sign. Python adds nothing between them, so add a space yourself if you want one.

python
x = "wireless"
y = "network"
print(x + y)
print(x + " " + y)
output
wirelessnetwork
wireless network

You can also repeat a string with a star:

python
print("ha" * 3)
output
hahaha

Strings as Sequences: Indexing

Strings behave like an ordered collection of characters, so you can pick one character by its position. They are not Python arrays, but they do support indexing in the same way. Here is how python is numbered:

How python is numbered
Letter p y t h o n
From the left 0 1 2 3 4 5
From the right -6 -5 -4 -3 -2 -1
python
a = "python"
print(a[0], a[2], a[-1])
print(len(a))
output
p t n
6

A single character is itself a string of length 1. A string that starts with a space gives a space at position 0, so check for stray spaces when an index looks wrong.

Strings Cannot Be Changed

Try to change a character in place and Python refuses:

python
a = "python"
try:
    a[0] = "P"
except TypeError as error:
    print("TypeError:", error)
output
TypeError: 'str' object does not support item assignment

To get a changed version, build a new string, for example "P" + a[1:] gives Python.

String Slicing

Slicing cuts a piece out of a string. The pattern is string[start:end:step]. The start position is included, and the end position is not. Leave out a number and Python uses the beginning or end. Negative numbers count from the right.

python
a = "python"
print(a[2:])
print(a[1:4])
print(a[-4:-2])
print(a[:3])
print(a[::2])
print(a[::-1])
output
thon
yth
th
pyt
pto
nohtyp
Slice examples for python
Slice Meaning Result for python
a[2:] From position 2 to the end thon
a[1:4] Positions 1, 2 and 3 yth
a[-4:-2] From 4th last up to, not including, 2nd last th
a[:3] From the start up to, not including, 3 pyt
a[::2] Every second character pto
a[::-1] Step backward, which reverses the string nohtyp

String Functions in Python

Strings come with many built in methods. A method is called with a dot after the string. Python is case sensitive, so the names are all lowercase, strip and not Strip. Remember that methods do not change the original string. They return a new one.

strip()

strip removes spaces, tabs and new lines from both ends. lstrip does the left end only, and rstrip the right end only. Here the repr function shows the spaces:

python
b = "   Hello python   "
print(repr(b.strip()), repr(b.lstrip()), repr(b.rstrip()))
output
'Hello python' 'Hello python   ' '   Hello python'

len()

len is a function, not a string method. It counts the characters, including spaces.

python
print(len("Pythonworld"))
output
11

lower() and upper()

They change the case of every letter, and keep spaces.

python
t = "Hello PyThon"
print(t.lower())
print(t.upper())
print(t.title())
print("hello world".capitalize())
output
hello python
HELLO PYTHON
Hello Python
Hello world

title makes the first letter of every word a capital. capitalize does it only for the first letter of the whole string.

replace()

replace swaps every matching part of the string for new text.

python
print("Tree".replace("T", "F"))
output
Free

format() and f Strings

format fills the curly braces in a string with values. The value can be a number, text or anything else, not only a number.

python
score = 85
print("Your Maths Score is {}".format(score))
output
Your Maths Score is 85

Modern Python code usually uses f strings instead. Put the letter f before the opening quote and write the name inside braces. You can even do a calculation or set the format inside the braces.

python
score = 85
name = "Asha"
print(f"{name} scored {score} marks, which is {score / 100:.0%}")
output
Asha scored 85 marks, which is 85%

count()

count tells you how many times a piece of text appears.

python
c = "This string is immutable"
print(c.count("i"))
output
4

find() and index()

Both give the position where the text first appears. The difference is what happens when it is not found. find returns minus 1, and index raises a ValueError.

python
c = "This string is immutable"
print(c.find("is"))
print(c.find("zzz"))
try:
    c.index("zzz")
except ValueError as error:
    print("ValueError:", error)
output
2
-1
ValueError: substring not found

The first is at position 2, inside the word This.

split() and join()

split breaks a string into a list of pieces at the text you give. With no argument, it splits on spaces. join does the opposite. It glues a list of strings together, using the string it is called on as the glue.

python
print("Primary".split("r"))
words = "to be or not to be".split()
print(words)
print("-".join(words))
output
['P', 'ima', 'y']
['to', 'be', 'or', 'not', 'to', 'be']
to-be-or-not-to-be

startswith() and endswith()

These check how a string begins or ends. Note that startswith checks only the beginning, so it does not test whether a character is present anywhere.

python
print("network".startswith("w"), "wireless".startswith("w"), "wireless".endswith("ss"))
output
False True True

Checking With in and not in

To check whether a character or phrase appears anywhere in a string, use the in word. Use not in for the opposite. Both give True or False.

python
sentence = "Strings are immutable but lists are mutable"
print("are" in sentence, "sets" in sentence, "are" not in sentence, "sets" not in sentence)
output
True False False True

Other Handy Checks

python
print("123".isdigit(), "abc".isalpha(), "abc123".isalnum())
output
True True True

Escape Characters and Raw Strings

A backslash gives a special meaning to the character after it. It lets you put quotes inside a string and add new lines. A raw string, with an r before the quote, turns this off, which is useful for file paths.

python
print("She said \"hi\"")
print("Line one\nLine two")
print(r"C:\new\table")
output
She said "hi"
Line one
Line two
C:\new\table

Quick Reference

String methods at a glance
Method What it does Example result
strip() Removes spaces from both ends ‘Hello python’
lower(), upper() Changes case hello python
title() Capital letter on each word Hello Python
replace(old, new) Swaps matching text Free
find(text) Position of text, or minus 1 2
index(text) Position of text, or an error 2
count(text) How often text appears 4
split(sep) Breaks into a list [‘P’, ‘ima’, ‘y’]
join(list) Glues a list into a string to-be-or-not
startswith(), endswith() Checks the beginning or end True

Common Mistakes

  • Using curly quotes. They look right, but Python rejects them. Type straight quotes in a code editor.
  • Trying to change a character in place. Strings are immutable, so build a new string.
  • Forgetting that methods return a new string. Writing text.upper() alone changes nothing. Save it with text = text.upper().
  • Forgetting the space when joining. x + y gives wirelessnetwork.
  • Capital letters in method names. Write strip, not Strip.
  • Mixing up the end of a slice. The end position is not included.
  • Using index when the text may be missing. It raises an error. Use find, or check with in first.
  • Joining text and numbers with plus. "Score: " + 85 is a TypeError. Use an f string.

Try It Yourself: The Full Program

The program below holds every example in this tutorial. Copy it into a file, run it, and compare the output with what you see above.

python
import sys
print("Python", sys.version_info.major, sys.version_info.minor)

# Creating strings
print('Python')
print("Python")
print('''Python''')
text = "python"
print(text)

# Multiline
poem = """Welcome to
the python
world"""
print(poem)

# Joining and repeating
x = "wireless"
y = "network"
print(x + y)
print(x + " " + y)
print("ha" * 3)

# Indexing: each character has a position, starting at 0
a = "python"
print(a[0], a[2], a[-1])
print(len(a))
try:
    a[0] = "P"
except TypeError as error:
    print("TypeError:", error)

# Slicing
print(a[2:])
print(a[1:4])
print(a[-4:-2])
print(a[:3])
print(a[::2])
print(a[::-1])

# Cleaning and changing case
b = "   Hello python   "
print(repr(b.strip()), repr(b.lstrip()), repr(b.rstrip()))
t = "Hello PyThon"
print(t.lower())
print(t.upper())
print(t.title())
print("hello world".capitalize())
print("Tree".replace("T", "F"))

# Formatting
score = 85
print("Your Maths Score is {}".format(score))
name = "Asha"
print(f"{name} scored {score} marks, which is {score / 100:.0%}")

# Searching and counting
c = "This string is immutable"
print(c.count("i"))
print(c.find("is"))
print(c.find("zzz"))
try:
    c.index("zzz")
except ValueError as error:
    print("ValueError:", error)

# Splitting and joining
print("Primary".split("r"))
words = "to be or not to be".split()
print(words)
print("-".join(words))

# Testing
print("network".startswith("w"), "wireless".startswith("w"), "wireless".endswith("ss"))
sentence = "Strings are immutable but lists are mutable"
print("are" in sentence, "sets" in sentence, "are" not in sentence, "sets" not in sentence)
print("123".isdigit(), "abc".isalpha(), "abc123".isalnum())

# Escape characters and raw strings
print("She said \"hi\"")
print("Line one\nLine two")
print(r"C:\new\table")

Strings are everywhere in Python, and now you know how to create them, cut them, search them and clean them. The best way to learn is to type each example, change it, and see what happens. When you are comfortable, move on to lists, tuples and dictionaries, which store collections of values, and then to reading and writing text files.

Popular Tags:

How to Assign String to a Variable Multiline Strings in Python Python Strings Tutorials with Examples String Functions in Python String Literals in Python