CHAPTER 8:
STRINGS
CHAPTER 8:
STRINGS
INTRODUCTION
ACCESSING CHARACTERS
STRING IS IMMUTABLE
STRING OPERATIONS
STRING METHODS AND BUILT-IN
FUNCTIONS
HANDLING STRING
INTRODUCTION
Definition: A string is a sequence of Unicode characters, including letters, digits,
whitespaces, and symbols. Strings can be created using single, double, or triple
quotes.
Example:
str1 = 'Hello World!’
str2 = "Hello World!“
str3 = """Hello World!""“
str4 = '''Hello World!’‘’
NOTE: UNDERSTANDING THIS CHAPTER IS CRUCIAL TO UNDERSTAND LIST, TUPLE
AND DICTIONARIES.
ACCESSING CHARACTERS IN A STRING
Indexing: Characters in a string can be accessed using indices.
Positive indices start from 0 on the left, and negative indices start from -1 on the
right.
Example:
str1 = 'Hello World!’
print(str1[0]) # Output: 'H’
print(str1[-1]) # Output: '!'
STRING IS IMMUTABLE
Immutability: Strings cannot be modified after creation. Any attempt to alter a string
results in an error.
Example:
str1 = "Hello World!“
str1[1] = 'a' # Raises TypeError
STRING OPERATIONS
THERE ARE FIVE OPERATIONS THAT WE CAN PERFORM ON A STRING:
CONCATENATION OPERATION
REPITITION OPERATION
MEMBERSHIP OPERATION
SLICING OPERATION
TRAVERSING OPERATION
CONCATENATION OPERATION
Joining Strings: Concatenate using the + operator.
Example:
str1 = 'Hello’
str2 = 'World!’
print(str1 + str2) # Output: 'HelloWorld!’ (NOTE: SPACE IS NOT THERE IN BETWEEN)
REPITITION OPERATION
Repeating Strings: Use the * operator to repeat a string.
Example:
str1 = 'Hello’
print(str1 * 2) # Output: 'HelloHello'
MEMBERSHIP OPERATION
Checking Substring: Use in and not in to check if a substring exists within a string.
Example:
str1 = 'Hello World!’
print('W' in str1) # Output: True
SLICING OPERATION
Basic Slicing Negative Index Slicing
Extracting Substrings: Use str[start:end] Using Negative Indices: Negative indices
to extract a part of the string starting can be used to slice strings from the end.
from index start up to, but not including, str[-start:-end] starts from the end of the
index end. string.
str1 = "Hello World"
str1 = "Hello World" print(str1[-5:-1]) # Output: "Worl"
print(str1[1:5]) # Output: "ello"
SLICING OPERATION
Step Slicing Positive Indices:
Skipping Characters: Use a third str1 = "Hello World"
parameter to specify the step, allowing
you to skip characters in the slicing print(str1[0:5]) # Output: "Hello"
operation. str[start:end:step] extracts print(str1[6:]) # Output: "World"
characters from start to end in steps of
step. print(str1[:5]) # Output: "Hello"
str1 = "Hello World"
print(str1[Link]) # Output: "HloWr"
SLICING OPERATION
Negative Indices: Mixing Positive and Negative Indices:
str1 = "Hello World" str1 = "Hello World"
print(str1[-5:]) # Output: "World" print(str1[1:-1]) # Output: "ello Worl"
print(str1[:-6]) # Output: "Hello" print(str1[-11:-6]) # Output: "Hello"
print(str1[-5:-1]) # Output: "Worl"
TRAVERSING OPERATION
Using Loops: Traverse a string using for or while loops. Traversing involves accessing
each element of the string once.
Example:
for ch in str1:
print(ch, end='')
STRING METHODS & BULIT-IN FUNCTIONS
Common Methods: lower(): Converts all characters to lowercase.
len(): Returns the length of the string. str1 = 'Hello World!'
str1 = 'Hello World!' print([Link]()) # Output: 'hello world!'
print(len(str1)) # Output: 12
upper(): Converts all characters to
uppercase.
title(): Converts the first character of each
word to uppercase. str1 = 'Hello World!'
str1 = 'hello world!' print([Link]()) # Output: 'HELLO
WORLD!'
print([Link]()) # Output: 'Hello World!'
STRING METHODS AND BUILT-IN FUNCTIONS
count(): Counts the occurrences of a substring. index(): Similar to find() but raises an
exception if the substring is not found.
str1 = 'Hello World! Hello!'
str1 = 'Hello World!'
print([Link]('Hello')) # Output: 2
print([Link]('World')) # Output: 6
# print([Link]('Python')) # Raises
find(): Finds the first occurrence of a ValueError
substring.
str1 = 'Hello World!'
endswith(): Checks if the string ends with a
print([Link]('World')) # Output: 6 specified substring.
str1 = 'Hello World!'
print([Link]('!')) # Output: True
STRING METHODS AND BUILT-IN FUNCTIONS
startswith(): Checks if the string starts islower(): Checks if all characters are
with a specified substring. lowercase.
str1 = 'Hello World!' str1 = 'hello world!'
print([Link]('Hello')) # Output: print([Link]()) # Output: True
True
isupper(): Checks if all characters are
isalnum(): Checks if all characters are uppercase.
alphanumeric.
str1 = 'HELLO WORLD!'
str1 = 'HelloWorld123'
print([Link]()) # Output: True
print([Link]()) # Output: True
STRING METHODS AND BUILT-IN FUNCTIONS
lstrip(), rstrip(), strip(): Remove spaces from the
left, right, or both sides of the
str1 = ' Hello World! '
print([Link]()) # Output: 'Hello World! '
print([Link]()) # Output: ' Hello World!'
print([Link]()) # Output: 'Hello World!'
replace(): Replaces occurrences of a substring
with another substring.
str1 = 'Hello World!'
print([Link]('World', 'Python')) # Output:
'Hello Python!'
STRING METHODS AND BUILT-IN FUNCTIONS
join(): Joins elements of a sequence with a specified separator.
str_list = ['Hello', 'World', '!']
print(' '.join(str_list)) # Output: 'Hello World !'
partition(): Splits the string into three parts around a specified substring.
str1 = 'Hello World!'
print([Link]('World'))
# Output: ('Hello ', 'World', '!')
split(): Splits the string into a list of substrings.
str1 = 'Hello World!'
print([Link]()) # Output: ['Hello', 'World!']
STRING HANDLING: EXAMPLE
Counting character occurrences:
def charCount(ch, st):
count = 0
for character in st:
if character == ch:
count += 1
return count
st = input("Enter a string: ")
ch = input("Enter the character to be searched: ")
count = charCount(ch, st)
print("Number of times character", ch, "occurs in the string is:", count)
STRING HANDLING: MORE EXAMPLES
Counting characters, alphabets, digits, special symbols, and words in a text.
Converting a string to title case.
Deleting all occurrences of a character from a string.
Summing digits in a string.
Replacing spaces with hyphens in a sentence.
CHAPTER BLUEPRINT
VSA SA LA E TOTAL
1 MARK 2 MARKS 3 MARKS 5 MARKS
1 MCQ -------- 1 -------- 4 MARKS