Strings in Python
An example of a literal constant is a number like 5 , 1.23 , or a string like 'This is a string' or "It's a string!" .
What is a String?
A string is a sequence of characters. In Python, a string is one of the most fundamental data types you will use. Strings are basically just a bunch of words—or more precisely, any sequence of text characters strung together.
A string literal is a string value that you write directly in your code. You can create a string by enclosing text in either single quotes or double quotes. For example, 'This is a string' and "It's a string!" are both valid string literals. The choice between single and double quotes is mostly a matter of style, but double quotes are useful when your string contains an apostrophe, since using double quotes avoids the need to escape the apostrophe.
You will be using strings in almost every Python program that you write. Understanding how strings work is essential to becoming proficient in Python.
Accessing Characters: Indexing
Each character in a string occupies a position, called an index. Python uses zero-based indexing, meaning the first character is at index 0, the second at index 1, and so on. You can access a single character by writing the string (or a variable holding a string) followed by square brackets containing the index number.
Python also supports negative indexing. A negative index counts backward from the end of the string. The last character is at index -1, the second-to-last at -2, and so on. This is convenient when you want to access characters near the end without needing to know the string's length.
Extracting Substrings: Slicing
Slicing allows you to extract a contiguous portion of a string. The syntax is string[start:end], where start is the index of the first character to include and end is the index of the first character to exclude. In other words, the slice includes characters from start up to but not including end. If you omit start, slicing begins at index 0. If you omit end, slicing continues to the last character.
If you have the string 'Hello' and write 'Hello'[1:4], you get 'ell'. The slice starts at index 1 (the character 'e') and continues up to but not including index 4 (the character 'o'). This off-by-one behavior at the end index is intentional in Python and makes many string operations more intuitive once you get used to it.
Why Strings Cannot Be Changed: Immutability
Strings in Python are immutable, meaning once a string is created, you cannot change any of its characters. If you try to assign a new value to a character using indexing—for example, my_string[0] = 'X'—Python will raise an error. This design choice makes strings safer and more efficient in many situations.
When you want to modify a string, you must create a new string and reassign it to your variable. For example, if greeting = 'Hello' and you want to change the first character to 'J', you would write greeting = 'J' + greeting[1:], which creates a new string 'Jello' and assigns it back to the variable greeting. The original string 'Hello' still exists in memory but is no longer referenced by your variable.
Special Characters and Escape Sequences
Some characters cannot be typed directly into a string literal. For example, to include a newline, a tab, or a quote character inside a string, you use an escape sequence—a backslash followed by a special character. The most common escape sequences are \n for newline, \t for tab, \' for a single quote, and \" for a double quote. When Python reads an escape sequence, it interprets it as the single character it represents, not as two separate characters.
If you write print('Hello\nWorld'), Python interprets \n as a single newline character and prints Hello on one line and World on the next. The escape sequence \n is not printed as the two characters backslash and n; it is converted to an actual line break. Similarly, print('Name:\tAlice') uses \t to insert a tab character, creating horizontal spacing between Name: and Alice.
Common Mistakes with Strings
Forgetting that indexing is zero-based
Python, like most programming languages, starts counting from 0. The character 'P' is at index 0, 'y' is at index 1, and so on.
Fix:
Always remember that the first character is at index 0. If you need the nth character, use index n-1.Trying to modify a string by assigning to an index
Strings are immutable in Python. You cannot change a character in place. This will raise a TypeError.
Fix:
Create a new string using slicing and concatenation, then reassign it to your variable: my_string = 'X' + my_string[1:]Confusing the end index in a slice with the number of characters
The end index is exclusive, meaning the character at that index is not included. [0:3] gives you characters at indices 0, 1, and 2—three characters total.
Fix:
Remember that slicing includes the start index but excludes the end index. To get n characters starting at index i, use [i:i+n].Forgetting to escape quotes inside a string
Python sees the apostrophe as the end of the string literal and becomes confused about what comes after.
Fix:
Either use double quotes: "It's a string" or escape the apostrophe: 'It\'s a string'
Strings as Literal Constants
A string literal is a string value that appears directly in your code, written with quotes. Examples include 'Hello', "World", and 'Python 3'. These are literal constants, meaning they have a fixed value that you specify in the code itself. This is different from a variable that holds a string, such as message = 'Hello', where message is a variable name and 'Hello' is the string literal assigned to it.
In the code name = 'Alice', the string literal is 'Alice' (the actual text with quotes), and name is the variable that stores a reference to that string. You can reassign name to a different string literal, like name = 'Bob', but the literal 'Alice' itself never changes—it is just a constant value in your code.
Practice: Working with Strings
Given the string word = 'Programming', answer the following questions: What character is at index 0? What does word[3:7] return? How would you create a new string that replaces the first character with 'X'? Write out the Python code for each answer.
Hints
- Remember that indexing starts at 0.
- For slicing, the end index is exclusive.
- To modify a string, use slicing and concatenation to create a new string.
Write a Python expression that extracts the last three characters of a string stored in the variable text without using the len() function. Hint: use negative indexing.
Hints
- Negative indices count backward from the end.
- The last character is at index -1.
- You can use slicing with negative indices.
Key Takeaways
- A string is a sequence of characters, created using single or double quotes, and is one of the most fundamental data types in Python.
- Use zero-based indexing to access individual characters (e.g., my_string[0] for the first character) and negative indexing to count from the end (e.g., my_string[-1] for the last character).
- Slicing extracts a substring using the syntax string[start:end], where the start index is included and the end index is excluded.
- Strings are immutable, meaning you cannot change a character in place; instead, create a new string and reassign it to your variable.
- Escape sequences like \n, \t, and \' represent special characters that cannot be typed directly into a string literal.