Chapter 08: Strings
8.1 Introduction
In programming, data is not always numeric.
Real-world programs deal with:
- names of students
- addresses
- messages
- passwords
- search terms
- sentences and paragraphs
Such data consists of characters, not numbers.
To represent and manipulate textual data, Python provides the string data type.
A string is one of the most commonly used data types in Python, and understanding it well is essential for:
- input handling
- data validation
- text processing
- file handling (later chapters)
8.2 Strings
What Is a String?
A string is a sequence of characters enclosed within quotes.
In Python, a character itself is treated as a string of length 1.
Strings can be created using:
- single quotes
' ' - double quotes
" " - triple quotes
''' '''or""" """
Creating Strings
name = "Amit"
subject = 'Computer Science'
Both are valid and equivalent.
Why Python Allows Multiple Quotes
This flexibility allows us to include quotes inside strings without confusion.
msg1 = "It's a sunny day"
msg2 = 'He said, "Hello"'
Multi-line Strings
Triple quotes allow strings to span multiple lines.
address = """NCERT
New Delhi
India"""
These are commonly used for:
- long messages
- documentation strings
- formatted output
Strings Are Immutable (Very Important Concept)
Once a string is created, it cannot be changed.
s = "Python"
You cannot modify individual characters:
s[0] = "J" # ❌ TypeError
Why?
Because strings are immutable objects. Any operation that appears to “change” a string actually creates a new string.
This concept explains many behaviors students find confusing later.
Length of a String
The length of a string is the number of characters it contains.
s = "Python"
print(len(s)) # 6
Spaces are also characters:
s = "Hello World"
print(len(s)) # 11
8.3 String Operations
Strings support several operations that allow us to combine, compare, and repeat them.
8.3.1 Concatenation (+)
Concatenation joins two strings end to end.
first = "Computer"
second = "Science"
result = first + " " + second
print(result)
Output:
Computer Science
Important:
- Both operands must be strings
Python does not auto-convert numbers to strings
# print("Age: " + 15) ❌ TypeError print("Age: " + str(15))
8.3.2 Repetition (*)
Repeats a string multiple times.
s = "Hi "
print(s * 3)
Output:
Hi Hi Hi
8.3.3 Comparison of Strings
Strings can be compared using relational operators.
print("apple" == "apple") # True
print("Apple" == "apple") # False
Comparison is:
- case-sensitive
based on Unicode values
print("Zoo" > "apple") # False
This explains why sorting words sometimes gives unexpected results.
8.3.4 Membership Operators (in, not in)
Used to check whether a substring exists in a string.
s = "Computer Science"
print("Science" in s) # True
print("Math" not in s) # True
This is widely used in:
- searching
- validation
- filtering text
8.4 Traversing a String
What Does Traversing Mean?
Traversing a string means accessing its characters one by one.
Since strings are sequences, each character has an index.
Indexing
- Index starts from
0 Negative indexing starts from
-1s = "Python" print(s[0]) # P print(s[3]) # h print(s[-1]) # n
Traversing Using for Loop
s = "Python"
for ch in s:
print(ch)
Explanation:
- Python automatically gives one character at a time
- No index handling needed
Traversing Using Index and range()
s = "Python"
for i in range(len(s)):
print(i, s[i])
This method is useful when:
- index position matters
- you need both index and character
Reverse Traversal
s = "Python"
for i in range(len(s) - 1, -1, -1):
print(s[i])
8.5 String Methods and Built-in Functions
Python provides many built-in methods for string processing.
Because strings are immutable, these methods return new strings.
Case Conversion Methods
s = "Computer Science"
print(s.upper())
print(s.lower())
print(s.title())
print(s.capitalize())
Searching Methods
s = "Computer Science"
print(s.find("Science")) # starting index
print(s.find("Math")) # -1 (not found)
Checking Content (Very Important)
print("abc".isalpha()) # True
print("123".isdigit()) # True
print("abc123".isalnum()) # True
print(" ".isspace()) # True
Used heavily in input validation.
Splitting and Joining
line = "Python is easy"
words = line.split()
print(words)
joined = "-".join(words)
print(joined)
Stripping Extra Spaces
s = " Hello "
print(s.strip())
print(s.lstrip())
print(s.rstrip())
Built-in Functions on Strings
s = "Python"
print(len(s))
print(max(s))
print(min(s))
print(sorted(s))
These functions work because strings are iterable sequences.
8.6 Handling Strings
This section focuses on practical string handling, combining multiple concepts.
Example 1: Counting Vowels
s = input("Enter a string: ")
count = 0
for ch in s:
if ch.lower() in "aeiou":
count += 1
print("Number of vowels:", count)
Concepts used:
- traversal
- membership operator
- case conversion
Example 2: Palindrome Check
s = input("Enter a string: ")
rev = ""
for ch in s:
rev = ch + rev
if s == rev:
print("Palindrome")
else:
print("Not a palindrome")
Example 3: Removing Spaces
s = input("Enter a string: ")
result = ""
for ch in s:
if ch != " ":
result += ch
print(result)
Example 4: Frequency of Characters
s = input("Enter a string: ")
for ch in s:
print(ch, ":", s.count(ch))
(Improved versions using dictionaries come later.)
Key Conceptual Takeaways
- A string is a sequence of characters enclosed in single, double or triple quotes.
- Indexing is used for accessing individual characters within a string.
- The first character has the index 0 and the last character has the index n-1 where n is the length of the string. The negative indexing ranges from -n to -1.
- Strings in Python are immutable, i.e., a string cannot be changed after it is created.
- Membership operator in takes two strings and returns True if the first string appears as a substring in the second else returns False. Membership operator ‘not in’ does the reverse.
- Retrieving a portion of a string is called slicing. This can be done by specifying an index range. The slice operation str1[n:m] returns the part of the string str1 starting from index n (inclusive) and ending at m (exclusive).
- Each character of a string can be accessed either using a for loop or while loop.
- There are many built-in functions for working with strings in Python.