Strings in Python
Subject: Data Structures and Algorithms · Language: Python · Level: beginner · 7 min read
Understand Python strings, indexing, slicing, immutability, traversal, palindrome checks, and string DSA patterns.
A string is a sequence of characters. It can store a word, name, sentence, password, email, code, or any text. In DSA, strings are important because many problems test indexing, comparison, frequency counting, and pattern checking.
Strings use indexes just like lists. The first character is at index `0`, and the last character is at index `len(s) - 1`. A loop can visit each character one by one and perform checks such as vowel counting, digit counting, or searching.
Python strings are immutable. This means you cannot directly change one character inside the same string. If you write code that appears to modify a string, Python actually creates a new string. For repeated changes, using a list of characters and then joining is often better.
Palindrome checking is a common string problem. A palindrome reads the same from left to right and right to left. The best beginner approach is to compare characters from both ends using two pointers.
Frequency counting is another important pattern. If the string contains lowercase letters, a list of size 26 can count characters. If the string can contain any character, a dictionary is more flexible. This idea helps solve anagram and duplicate problems.
Students should also understand string comparison. Uppercase and lowercase letters are different, so `A` and `a` are not the same. If the problem says comparison should ignore case, convert the string using `lower()` or `upper()` first.
A string is a sequence of characters. Names, passwords, email IDs, sentences, roll numbers, and codes are all examples of strings.
Python provides powerful string handling features, so text-based programs are easy to write. Still, in DSA, string problems require careful thinking about indexes, comparison, character frequency, and how text changes inside loops.
Creating a String
A string can be written using single quotes or double quotes.
```python
name = "PrepCampus"
word = 'Python'
```
Both styles are valid. Use one style consistently so the code looks clean.
String Indexing
String indexing starts from 0. For a string of length `n`, the last valid index is `n - 1`.
For example, in `Python`, index `0` stores `P`, index `1` stores `y`, and index `5` stores `n`.
```python
word = "Python"
print(word[0])
print(word[5])
```
Output
```text
P
n
```
If you try to access an index outside the valid range, Python raises an `IndexError`.
Negative Indexing
Python supports negative indexing for strings. `word[-1]` gives the last character.
```python
word = "Python"
print(word[-1])
```
Output
```text
n
```
This prints `n`.
String Length
Use `len()` to find how many characters are in a string.
```python
word = "Python"
print(len(word))
```
Output
```text
6
```
This prints `6`.
String Slicing
Slicing extracts part of a string using `start:end`.
```python
word = "Python"
print(word[1:4])
```
Output
```text
yth
```
This prints characters from index 1 to index 3. The ending index is not included.
Reversing a String
Python slicing can reverse a string using `[::-1]`.
```python
word = "level"
print(word[::-1])
```
Output
```text
level
```
This is useful for simple palindrome checks.
Strings Are Immutable
In Python, strings are immutable. That means once a string is created, its characters cannot be changed directly.
```python
word = "Python"
# word[0] = "J" # This is not allowed
```
If you need a changed string, create a new string. For many repeated changes, build a list of characters and then use `join()`.
Traversing a String
Traversal means visiting each character one by one.
```python
word = "Java"
for ch in word:
print(ch)
```
Output
```text
J
a
v
a
```
Use this pattern when counting vowels, checking characters, or building a new string.
You can also traverse with indexes.
```python
for i in range(len(word)):
print(i, word[i])
```
Sample Output when `word = "Java"`
```text
0 J
1 a
2 v
3 a
```
Use indexes when position matters.
Common String Methods
- `lower()` converts letters to lowercase
- `upper()` converts letters to uppercase
- `strip()` removes extra spaces from beginning and end
- `split()` breaks a string into parts
- `join()` joins strings together
- `replace()` replaces one part with another
- `find()` returns the index of a substring if found
These methods are useful in real programs and many string practice questions.
Comparing Strings
Strings can be compared using `==` for equal value.
```python
a = "python"
b = "python"
print(a == b)
```
Output
```text
True
```
This prints `True` because both strings have the same content.
Palindrome String
A palindrome string reads the same from left to right and right to left. Examples are `level`, `madam`, and `racecar`.
The easiest Python check is comparing the string with its reverse.
```python
word = input()
if word == word[::-1]:
print("Palindrome")
else:
print("Not Palindrome")
```
Sample Input
```text
level
```
Output
```text
Palindrome
```
A two-pointer approach is also useful because it teaches DSA logic and can avoid creating a reversed copy.
Character Frequency
Frequency means how many times something appears. In string problems, character frequency is used to count letters.
```python
freq = {}
for ch in "banana":
freq[ch] = freq.get(ch, 0) + 1
```
Here, a dictionary stores each character and its count.
Strings in DSA
String problems are common in placement preparation because they test logic and careful indexing. A small index mistake can change the answer or cause an error.
Common string problems include vowel counting, palindrome checking, anagram checking, frequency counting, first non-repeating character, reversing words, and removing duplicates.
Example Program
```python
word = input("Enter a word: " )
if word == word[::-1]:
print("Palindrome")
else:
print("Not Palindrome")
```
Sample Input
```text
level
```
Output
```text
Enter a word: Palindrome
```
This program reads one word and checks whether it is a palindrome by comparing it with its reversed form.
String traversal is very common. A loop can visit each character, count vowels, check digits, build frequency, compare opposite ends, or find a target character. Most beginner string problems are solved using careful traversal.
A palindrome string reads the same from both sides. To check it manually, compare the first character with the last character, the second with the second-last, and continue until the pointers meet. This teaches two-pointer thinking.
Practice Question
Take a string as input and print the number of vowels, consonants, digits, and spaces.