Lesson 7 of 2014 min read

Strings

Share:WhatsAppLinkedIn

Prerequisites: Variables, data types, operators, loops, conditionals


1. What is a String?

A string is a sequence of characters enclosed in quotes. Strings are one of the most commonly used data types in Python.

# Strings are sequences of characters
name = "Python"
# Each character has a position (index)
# P y t h o n
# 0 1 2 3 4 5 (positive index)
#-6 -5 -4 -3 -2 -1 (negative index)

2. Creating Strings

2.1 Single Quotes

s1 = 'Hello'
print(s1)

Output:

Hello

2.2 Double Quotes

s2 = "Hello"
print(s2)

Output:

Hello

2.3 Triple Quotes (multi-line strings)

s3 = '''This is
a multi-line
string'''
print(s3)

Output:

This is
a multi-line
string

2.4 When to use which?

# Use double quotes when string contains single quote
msg1 = "It's a sunny day"

# Use single quotes when string contains double quote
msg2 = 'He said "Hello"'

# Use triple quotes when string contains both
msg3 = '''He said "It's fine"'''

# Empty string
empty = ""
print(len(empty)) # 0

3. Accessing Characters: Indexing

3.1 Positive Indexing (left to right, starts at 0)

s = "PYTHON"
print(s[0]) # P
print(s[1]) # Y
print(s[5]) # N
# print(s[6]) # IndexError: string index out of range

Output:

P
Y
N

3.2 Negative Indexing (right to left, starts at -1)

s = "PYTHON"
print(s[-1]) # N (last character)
print(s[-2]) # O (second last)
print(s[-6]) # P (first character)

Output:

N
O
P

3.3 Index Table

String: P Y T H O N
Index: 0 1 2 3 4 5
Neg: -6 -5 -4 -3 -2 -1

4. String Slicing: s[start:stop:step]

Slicing extracts a portion of the string. The general syntax is:

s[start : stop : step]
  • start, index where slice begins (included)
  • stop, index where slice ends (excluded)
  • step, how many characters to skip (default 1)

4.1 Basic Slicing

s = "COMPUTER"
# C O M P U T E R
# 0 1 2 3 4 5 6 7

print(s[2:5]) # MPU (index 2, 3, 4)
print(s[0:4]) # COMP (index 0, 1, 2, 3)

Output:

MPU
COMP

4.2 Omitting start or stop

s = "COMPUTER"

print(s[:5]) # COMPU (from beginning to index 4)
print(s[3:]) # PUTER (from index 3 to end)
print(s[:]) # COMPUTER (full copy)

Output:

COMPU
PUTER
COMPUTER

4.3 Using step

s = "COMPUTER"

print(s[::2]) # CMUE (every 2nd character)
print(s[1::2]) # OPTR (every 2nd, starting at index 1)
print(s[0:6:2]) # CMU (index 0 to 5, step 2)

Output:

CMUE
OPTR
CMU

4.4 Negative step (reverse)

s = "COMPUTER"

print(s[::-1]) # RETUPMOC (full reverse)
print(s[5:1:-1]) # TUPM (index 5 to 2, reversed)
print(s[-1::-1]) # RETUPMOC (another way to reverse)

Output:

RETUPMOC
TUPM
RETUPMOC

4.5 Slicing Summary Table

Slice Result for "PYTHON" Meaning
s[2:5] THO Index 2 to 4
s[:3] PYT First 3 characters
s[3:] HON From index 3 to end
s[::2] PTO Every 2nd character
s[::-1] NOHTYP Reversed string
s[1:5:2] YH Index 1 to 4, step 2

5. String Operations

5.1 Concatenation (+)

first = "Hello"
second = "World"
result = first + " " + second
print(result)

Output:

Hello World

Note: You can only concatenate string with string, not string with number.

# This will cause an error:
# print("Age: " + 25) # TypeError

# Correct way:
print("Age: " + str(25)) # Age: 25

5.2 Repetition (*)

print("ha" * 3)
print("-" * 20)

Output:

hahaha
--------------------

5.3 Membership (in / not in)

s = "Hello World"

print("H" in s) # True
print("hello" in s) # False (case-sensitive)
print("World" in s) # True
print("xyz" not in s) # True

Output:

True
False
True
True

6. Traversing a String with for Loop

6.1 Using for with variable

s = "HELLO"
for ch in s:
 print(ch, end=" ")

Output:

H E L L O

6.2 Using for with range and index

s = "HELLO"
for i in range(len(s)):
 print(f"s[{i}] = {s[i]}")

Output:

s[0] = H
s[1] = E
s[2] = L
s[3] = L
s[4] = O

7. Strings are IMMUTABLE

Once a string is created, you cannot change any character in it.

s = "Hello"
# s[0] = 'h' # TypeError: 'str' object does not support item assignment

# To "change" a string, create a new one:
s = 'h' + s[1:]
print(s) # hello

Output:

hello

Key point for exams: Strings cannot be modified in place. Every string operation creates a new string.


8. String Methods

8.1 len, Length of string

s = "Hello World"
print(len(s))

Output:

11

Note: len is a built-in function, not a method. It counts all characters including spaces.


8.2 capitalize, First character uppercase, rest lowercase

Syntax: string.capitalize

s = "hello WORLD"
print(s.capitalize)

Output:

Hello world

8.3 title, First letter of each word uppercase

Syntax: string.title

s = "hello world python"
print(s.title)

Output:

Hello World Python

8.4 lower, Convert to lowercase

Syntax: string.lower

s = "HELLO World"
print(s.lower)

Output:

hello world

8.5 upper, Convert to uppercase

Syntax: string.upper

s = "hello world"
print(s.upper)

Output:

HELLO WORLD

8.6 count, Count occurrences of substring

Syntax: string.count(sub[, start[, end]])

s = "hello world hello"
print(s.count("hello"))
print(s.count("l"))
print(s.count("l", 0, 5)) # search only in "hello"

Output:

2
4
2

8.7 find, Find first occurrence (returns -1 if not found)

Syntax: string.find(sub[, start[, end]])

s = "Hello World"
print(s.find("World")) # 6
print(s.find("Python")) # -1 (not found)
print(s.find("l")) # 2 (first occurrence)

Output:

6
-1
2

8.8 index, Find first occurrence (raises error if not found)

Syntax: string.index(sub[, start[, end]])

s = "Hello World"
print(s.index("World")) # 6
# print(s.index("Python")) # ValueError: substring not found

Output:

6

Difference: find returns -1 if not found; index raises ValueError.


8.9 endswith, Check if string ends with suffix

Syntax: string.endswith(suffix[, start[, end]])

s = "hello.py"
print(s.endswith(".py")) # True
print(s.endswith(".txt")) # False

Output:

True
False

8.10 startswith, Check if string starts with prefix

Syntax: string.startswith(prefix[, start[, end]])

s = "Hello World"
print(s.startswith("Hello")) # True
print(s.startswith("World")) # False

Output:

True
False

8.11 isalnum, True if all characters are alphanumeric

Syntax: string.isalnum

print("Hello123".isalnum) # True
print("Hello 123".isalnum) # False (space is not alphanumeric)
print("Hello!".isalnum) # False

Output:

True
False
False

8.12 isalpha, True if all characters are alphabets

Syntax: string.isalpha

print("Hello".isalpha) # True
print("Hello123".isalpha) # False
print("Hello World".isalpha)# False (space)

Output:

True
False
False

8.13 isdigit, True if all characters are digits

Syntax: string.isdigit

print("12345".isdigit) # True
print("123.45".isdigit) # False (dot is not a digit)
print("12 34".isdigit) # False (space)

Output:

True
False
False

8.14 islower, True if all cased characters are lowercase

Syntax: string.islower

print("hello".islower) # True
print("Hello".islower) # False
print("hello 123".islower) # True (digits ignored)

Output:

True
False
True

8.15 isupper, True if all cased characters are uppercase

Syntax: string.isupper

print("HELLO".isupper) # True
print("Hello".isupper) # False
print("HELLO 123".isupper) # True (digits ignored)

Output:

True
False
True

8.16 isspace, True if all characters are whitespace

Syntax: string.isspace

print(" ".isspace) # True
print(" \t\n ".isspace) # True
print(" a ".isspace) # False

Output:

True
True
False

8.17 lstrip, Remove leading (left) whitespace/characters

Syntax: string.lstrip([chars])

s = " Hello "
print(s.lstrip) # "Hello "
print("xxHelloxx".lstrip("x")) # "Helloxx"

Output:

Hello 
Helloxx

8.18 rstrip, Remove trailing (right) whitespace/characters

Syntax: string.rstrip([chars])

s = " Hello "
print(s.rstrip) # " Hello"
print("xxHelloxx".rstrip("x")) # "xxHello"

Output:

 Hello
xxHello

8.19 strip, Remove leading and trailing whitespace/characters

Syntax: string.strip([chars])

s = " Hello "
print(s.strip) # "Hello"
print("**Hello**".strip("*")) # "Hello"

Output:

Hello
Hello

8.20 replace, Replace occurrences of substring

Syntax: string.replace(old, new[, count])

s = "Hello World Hello"
print(s.replace("Hello", "Hi"))
print(s.replace("Hello", "Hi", 1)) # replace only first

Output:

Hi World Hi
Hi World Hello

8.21 join, Join elements of iterable with string as separator

Syntax: string.join(iterable)

print("-".join(["2025", "01", "15"]))
print(" ".join(["Hello", "World"]))
print(",".join("ABC")) # joins each character

Output:

2025-01-15
Hello World
A,B,C

8.22 partition, Split string into 3 parts at first occurrence

Syntax: string.partition(separator)

s = "Hello-World-Python"
print(s.partition("-"))
print(s.partition("=")) # separator not found

Output:

('Hello', '-', 'World-Python')
('Hello-World-Python', '', '')

8.23 split, Split string into list

Syntax: string.split([separator[, maxsplit]])

s = "Hello World Python"
print(s.split) # split by whitespace
print(s.split(" ", 1)) # split at first space only

csv = "a,b,c,d"
print(csv.split(","))

Output:

['Hello', 'World', 'Python']
['Hello', 'World Python']
['a', 'b', 'c', 'd']

9. String Methods Quick Reference Table

Method Purpose Returns
len(s) Length of string int
s.capitalize First char uppercase str
s.title Title case str
s.lower All lowercase str
s.upper All uppercase str
s.count(sub) Count occurrences int
s.find(sub) Find position (-1 if not found) int
s.index(sub) Find position (error if not found) int
s.endswith(suffix) Ends with suffix? bool
s.startswith(prefix) Starts with prefix? bool
s.isalnum All alphanumeric? bool
s.isalpha All alphabets? bool
s.isdigit All digits? bool
s.islower All lowercase? bool
s.isupper All uppercase? bool
s.isspace All whitespace? bool
s.lstrip Remove left whitespace str
s.rstrip Remove right whitespace str
s.strip Remove both sides whitespace str
s.replace(old, new) Replace substring str
s.join(iterable) Join with separator str
s.partition(sep) Split into 3 parts tuple
s.split(sep) Split into list list

10. Practice Programs

Program 1: Count vowels, consonants, uppercase, lowercase in string

s = input("Enter a string: ")

vowels = consonants = upper = lower = 0

for ch in s:
 if ch.isalpha:
 if ch.lower in "aeiou":
 vowels += 1
 else:
 consonants += 1
 if ch.isupper:
 upper += 1
 else:
 lower += 1

print("Vowels:", vowels)
print("Consonants:", consonants)
print("Uppercase:", upper)
print("Lowercase:", lower)

Sample Run:

Enter a string: Hello World
Vowels: 3
Consonants: 7
Uppercase: 2
Lowercase: 8

Program 2: Check if string is palindrome

s = input("Enter a string: ")

if s == s[::-1]:
 print(f"'{s}' is a palindrome")
else:
 print(f"'{s}' is not a palindrome")

Sample Run:

Enter a string: madam
'madam' is a palindrome

Alternative (case-insensitive, ignoring spaces):

s = input("Enter a string: ")
clean = s.lower.replace(" ", "")

if clean == clean[::-1]:
 print("Palindrome")
else:
 print("Not a palindrome")

Program 3: Reverse a string

# Method 1: Slicing
s = input("Enter a string: ")
print("Reversed:", s[::-1])

# Method 2: Using loop
s = input("Enter a string: ")
rev = ""
for ch in s:
 rev = ch + rev
print("Reversed:", rev)

# Method 3: Using loop (from end)
s = input("Enter a string: ")
rev = ""
for i in range(len(s) - 1, -1, -1):
 rev += s[i]
print("Reversed:", rev)

Sample Run:

Enter a string: Python
Reversed: nohtyP

Program 4: Convert case (upper to lower and vice versa)

# Method 1: Using swapcase (easy way, built-in)
s = input("Enter a string: ")
print(s.swapcase)

# Method 2: Manual (standard approach)
s = input("Enter a string: ")
result = ""
for ch in s:
 if ch.isupper:
 result += ch.lower
 elif ch.islower:
 result += ch.upper
 else:
 result += ch
print("Converted:", result)

Sample Run:

Enter a string: Hello World
Converted: hELLO wORLD

Program 5: Count words in a string

s = input("Enter a string: ")
words = s.split
print("Number of words:", len(words))

Sample Run:

Enter a string: Python is fun to learn
Number of words: 5

Alternative (without split):

s = input("Enter a string: ")
count = 0
in_word = False

for ch in s:
 if ch != ' ' and not in_word:
 count += 1
 in_word = True
 elif ch == ' ':
 in_word = False

print("Number of words:", count)

Program 6: Remove spaces from string

# Method 1: Using replace
s = input("Enter a string: ")
print(s.replace(" ", ""))

# Method 2: Using loop
s = input("Enter a string: ")
result = ""
for ch in s:
 if ch != ' ':
 result += ch
print(result)

# Method 3: Using join and split
s = input("Enter a string: ")
print("".join(s.split))

Sample Run:

Enter a string: Hello World Python
HelloWorldPython

Program 7: Find frequency of each character

s = input("Enter a string: ")

for ch in s:
 if s.index(ch) == s.rindex(ch) or s.index(ch) == s.find(ch):
 # Print frequency only once per unique character
 pass

# Better approach using a clean method:
s = input("Enter a string: ")
checked = ""

for ch in s:
 if ch not in checked:
 print(f"'{ch}' appears {s.count(ch)} time(s)")
 checked += ch

Sample Run:

Enter a string: hello
'h' appears 1 time(s)
'e' appears 1 time(s)
'l' appears 2 time(s)
'o' appears 1 time(s)

Program 8: Check if string contains only alphabets/digits

s = input("Enter a string: ")

if s.isalpha:
 print("String contains only alphabets")
elif s.isdigit:
 print("String contains only digits")
elif s.isalnum:
 print("String contains alphabets and digits")
else:
 print("String contains special characters or spaces")

Sample Run:

Enter a string: Hello123
String contains alphabets and digits

11. Common Mistakes

Mistake Why it is wrong Correct way
s[0] = 'H' Strings are immutable s = 'H' + s[1:]
"Age: " + 25 Cannot concatenate str and int "Age: " + str(25)
Using index without checking Raises error if not found Use find or check with in first
s.upper expecting s to change Methods return new string s = s.upper
s[-0] expecting last character -0 is same as 0 Use s[-1] for last character
Forgetting split returns list Cannot use string methods on list Process list elements individually

$1$2 Quick Tips

  1. Slicing is the most commonly tested topic. Practice all combinations of start, stop, step, especially negative step for reversal.

  2. Know the difference between find and index, exams frequently ask this.

  3. Remember: strings are immutable. Any operation that appears to modify a string actually creates a new one.

  4. len is a function, not a method. Write len(s), not s.len.

  5. Common output questions: Given a string and a series of operations, predict the output. Practice tracing through code carefully.

  6. split and join are complementary. "a,b,c".split(",") gives ['a','b','c'] and ",".join(['a','b','c']) gives "a,b,c".

  7. For programs that process characters: Always consider whether the problem requires you to handle uppercase and lowercase separately or together (use .lower or .upper to normalize).

  8. partition always returns a tuple of 3 elements, even if the separator is not found (the original string, empty string, empty string).

Test Your Knowledge

Take a quick quiz on this lesson

Start Quiz →

Prefer watching over reading?

Subscribe for free.

Subscribe on YouTube