A string is a sequence of characters used to store text, such as a name, a sentence, an email address, or the contents of a file. Strings are one of the most used data types in Python. Almost every program reads, builds, cleans, or prints text.
In this guide, you’ll learn how to create strings, access their characters, combine and compare them, work with special characters, and avoid the mistakes beginners make most often.
Key terms used in this article:
- String: An ordered, immutable sequence of Unicode characters. Its type is
str. - Character: A single letter, digit, symbol, space, or emoji. Python has no separate character type: a character is a string of length 1.
- Index: The position of a character in a string. The first character is at index
0. - Immutable: Can’t be changed after it’s created. String methods return new strings instead of changing the original.
- Escape sequence: A backslash followed by a character, such as
\n(new line), that represents a special character.
Table of contents
- Creating strings
- Escape sequences
- Raw strings
- Accessing characters with indexing
- Slicing strings
- Strings are immutable
- String operations
- Looping through a string
- Common string methods
- Splitting and joining strings
- Formatting strings
- Checking the content of a string
- Unicode, encoding, and bytes
- Building strings efficiently
- Useful constants in the string module
- Common mistakes
- Practice exercises
- Summary
Creating strings
Wrap text in single quotes, double quotes, or triple quotes. Single and double quotes behave exactly the same:
Output:
Jessa London <class 'str'> 0
Choose the quote style that avoids escaping. Use double quotes when the text contains an apostrophe, and single quotes when it contains double quotes:
Output:
It's a sunny day She said "hello" to me
Multi-line strings
Triple quotes (""" or ''') let a string span several lines. The line breaks are kept in the string:
Output:
PYnative 221B Baker Street London
Triple-quoted strings are also used for docstrings, the documentation strings at the top of functions, classes, and modules.
Creating strings from other values
str() converts almost any value to a string:
Output:
28 years Price: 9.99 [1, 2, 3] True
Escape sequences
A backslash \ starts an escape sequence, which represents a character that’s hard to type directly.
| Escape sequence | Meaning |
|---|---|
\n | New line |
\t | Tab |
\\ | Backslash |
\' | Single quote |
\" | Double quote |
\r | Carriage return |
\uXXXX | Unicode character by hex code, such as \u20ac for € |
\N{name} | Unicode character by name, such as \N{GREEK SMALL LETTER PI} |
Output:
Line 1 Line 2 Name: Jessa C:\Users\Jessa It's fine Price: €9.99 Circle area = π r²
Raw strings
Prefix a string with r to create a raw string, where backslashes are treated as normal characters. Raw strings are ideal for Windows paths and regular expressions:
Output:
C: ew_folder est.txt C:\new_folder\test.txt
A raw string can’t end with an odd number of backslashes, so r"C:\folder\" is a SyntaxError. Use "C:\\folder\\" or add the trailing backslash separately.
Accessing characters with indexing
Each character has a position called an index. Python counts from 0 from the left, and from -1 from the right:
P y t h o n 0 1 2 3 4 5 -6 -5 -4 -3 -2 -1
Output:
P h n o n
Using an index that doesn’t exist raises an IndexError:
Output:
Error: string index out of range
Slicing strings
A slice extracts part of a string with the syntax string[start:stop:step]. The start index is included and the stop index is excluded:
Output:
Hello World Hello World Hlo ol dlroW ,olleH
Slicing never raises an IndexError, even if the indexes are out of range. Learn every slicing technique in String Slicing and Indexing in Python.
Strings are immutable
You can’t change a character in an existing string. Trying to assign to an index raises a TypeError:
Output:
Error: 'str' object does not support item assignment
Instead, build a new string and assign it to the variable:
Output:
Jython hello HELLO
Immutability makes strings safe to use as dictionary keys and set items, and lets Python share identical strings in memory.
String operations
Concatenation and repetition
+ joins strings, and * repeats a string:
Output:
Jessa Doe hahaha ==============================
You can only concatenate strings with strings. "Age: " + 28 raises a TypeError. Use str(28) or an f-string instead.
Length, membership, and counting
Output:
36 True True 2
Comparing strings
Strings are compared character by character using Unicode code points. Uppercase letters (A is 65) come before lowercase letters (a is 97):
Output:
True False True True True True
For case-insensitive comparisons of international text, use casefold() instead of lower().
Looping through a string
A string is iterable, so a for loop visits each character in order:
Output:
H i ! 0 a 1 b 2 c
Example: count the vowels in a sentence
Output:
9
Common string methods
Strings have dozens of built-in methods. Here are the ones you’ll use daily:
Output:
Learn Python Programming learn python programming LEARN PYTHON PROGRAMMING Learn Python Programming Learn Java Programming 8 True ['Learn', 'Python', 'Programming']
See Python String Methods for the full list with examples.
Splitting and joining strings
split() breaks a string into a list. join() does the opposite: it glues a list of strings together with a separator.
Output:
['Jessa', '28', 'London'] Python is awesome Python-is-awesome abc
join() only accepts strings. Convert numbers first, for example ", ".join(map(str, [1, 2, 3])).
Formatting strings
Use f-strings to insert values into a string. Put f before the quotes and the values in braces:
Output:
Kelly has $1,520.50 in her account
Kelly|
Learn every formatting option in Python f-Strings and String Formatting.
Checking the content of a string
Methods that start with is return True or False:
Output:
True True True True True True
Example: validate user input before converting it
Output:
'42' -> 42 '4.2' is not a whole number 'abc' is not a whole number '-7' -> -7
Unicode, encoding, and bytes
Python 3 strings are Unicode, so they can hold text in any language, plus symbols and emoji:
Output:
Hello 5 Hola 4 नमस्ते 6 こんにちは 5 Привет 6 65 a
len() counts Unicode code points, not visible letters. Some scripts, such as Hindi, combine several code points into one visible character, so len("नमस्ते") is 6.
To save text to a file or send it over a network, you encode it into bytes. To read it back, you decode the bytes into a string. UTF-8 is the standard encoding:
Output:
b'caf\xc3\xa9' 4 5 café
Always pass encoding="utf-8" when opening text files, for example open("notes.txt", encoding="utf-8"), so your program behaves the same on every operating system.
Building strings efficiently
Because strings are immutable, += in a loop creates a new string every time. For many pieces, collect them in a list and join once:
Output:
01234 01234
Useful constants in the string module
The string module provides ready-made sets of characters:
Output:
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
abcdefghijklmnopqrstuvwxyz
0123456789
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
Example: remove punctuation from a sentence
Output:
Hello World Pythons great
Common mistakes
- Forgetting that strings are immutable.
name.upper()doesn’t changename. Writename = name.upper(). - Adding strings and numbers.
"Total: " + 5raises aTypeError. Use an f-string. - Off-by-one slicing. The stop index is excluded, so
text[0:3]gives three characters. - Comparing numbers stored as text.
"10" < "9"isTrue. Convert withint()first. - Using backslashes in Windows paths without a raw string.
"C:\new"contains a newline. User"C:\new"or forward slashes. - Using
isto compare strings. Always compare text with==.
Practice exercises
Exercise 1: Check whether a word is a palindrome, ignoring case.
Output:
True
Exercise 2: Print the initials of a full name in uppercase, such as J.K.R. for joanne kathleen rowling.
Output:
J.K.R.
Exercise 3: Count how many times each character appears in a word.
Output:
{'m': 1, 'i': 4, 's': 4, 'p': 2}
Summary
- Create strings with single, double, or triple quotes. Use
str()to convert other values. - Use escape sequences such as
\nand\tfor special characters, and raw strings (r"...") to keep backslashes as they are. - Access characters by index (
s[0],s[-1]) and extract parts with slices (s[start:stop:step]). - Strings are immutable. Methods return new strings, so assign the result.
- Join with
+, repeat with*, check within, split withsplit(), and combine withjoin(). - Python strings are Unicode. Encode to bytes with
encode()and decode withdecode(), using UTF-8.
Also, See:

Leave a Reply