Working with strings as single things
A string is a sequence of characters enclosed in quotes.
It can include letters, numbers, symbols or spaces.
Strings can be created using either single ('...') or double ("...") quotes.
The str() function converts objects to their string representation.
Strings in Python are immutable, meaning once you define a string, you can’t change it
Ex: name = "Python"
print(name)
Working with the parts of a string
• The indexing operator (Python uses square brackets to enclose the index) selects a single
character
• substring from a string:
• Indexing: One way is to treat strings as a list and use index values
• Negative
-6 Indexing:
-5 Similar to-4a list, Python
-3 allows negative
-2 indexing
-1 for its strings
• P Y T H O N
0 1 2 3 4 5
Str=“PYTHON” Output:
print(Str[2])
print(Str[4])
print(Str[0])
print(Str[-5])
print(Str[-3])
print(Str[-4])
print(Str[-6])
• Enumerate():It returns pairs each index with its
character.
EX:
• Indexing in Python is a technique used to access individual elements of
a sequence (such as a string, list, or tuple) using their position (index
number).
The len() function:
• The string len() function returns the length of the string.
• The len() method is used to find the length of an object in Python.
• Positive Indexing (Left → Right) Starts from 0 and increases.
• Negative Indexing (Right → Left) Starts from -1 and decreases.
String len() Syntax
len(string)
Examples:
Examples:
Traversal and the for loop:
• String Traversal operations refers to process of one character at a time
Outpu Outpu
t t
String Slice
• A substring of a string is obtained by taking a slice.
• In this process, we extract a portion or piece of a string. Usually, we use the slice operator
"[ : ]" to perform slicing on a Python String
Ex:
SYNTAX:
string[start:stop:step].
•start:
•The index where the slice begins (inclusive). If
omitted, it defaults to the beginning of the string
(index 0).
•stop:
•The index where the slice ends (exclusive).
•step:
•The interval between characters to be included in
the slice
String comparison:
• Python string comparison compares the characters in both strings one
by one.
• You can compare strings in Python using the equality (==) and
comparison (<, >, !=, <=, >=) operators. There are no special
methods to compare two strings.
Strings
are immutable:
• Strings are immutable, which means you can’t change an existing string. The best you can
do is create a new string that is a variation on the original.
•The [] operator can be used to access characters (like greeting[0] → 'H'),
but it cannot be used to modify them.
• Strings are read-only sequences of characters.
• If we change the string means create a new one that contains the desired changes.
The in Operator — Checks Membership:
• The in operator checks whether a substring exists inside another
string
• It returns True if the substring is found, and False otherwise.
The not in operator:
• The not in operator checks if a specified substring does not exist within
another string.
• It returns True if the substring is not found, and False if it is found.
Advantage
• Easy to read and understand
• Short and simple code
• Useful in filtering or searching text
• Works for substrings (not just single characters)
Disadvantages
• Works only for exact order of characters
• Slightly slower for very long strings
EXAMPLES
Python String find() Method:
find() method in Python returns the index of the first occurrence of a substring within a given string. If the
substring is not found, it returns -1
Syntax of find() method
[Link](substring, start, end))
Parameter:
substring: The substring to search for within the main string s.
start (optional): The starting index from where to begin the search.
end (optional): The ending index where the search should stop.
Looping and counting
The following program counts the number of times the letter a appears in a string, and is
another example of the
counter pattern introduced in Counting digits:
Optional parameters
To find the locations of the second or third occurrence of a character in a string, we can
modify the find function, adding a third parameter for the starting position in the search
string
split() method :
• The split() method in Python is used to break a string into smaller parts (substrings) and store them in a list.
by default, it splits based on whitespace — that includes spaces, tabs, or newlines
• Splits a string into a list of strings after breaking the given string by the specified separator.
• It splits a single multi-word string into a list of individual words, removing all the whitespace between them.
Python String split() Method Syntax
Syntax: [Link](separator, maxsplit)
Parameters
•separator: This is a delimiter. The string splits at this specified separator. If is not
provided then any white space is a separator.
•maxsplit: It is a number, that tells us to split the string into a maximum of the
provided number of times. If it is not provided then the default is -1 which means there
is no limit
String Formats
• F-strings offer a concise and readable way to embed expressions directly into
string literals.
• They are prefixed with f or F.
[Link]() method
The format() method allows for more control over formatting and supports positional,
keyword, and mixed arguments. Placeholders are defined using curly braces {}.
The .format() method lets you insert values into a string using placeholders ({}).
Tuples
• A tuple in Python is an immutable ordered collection of elements.
•Tuples are similar to lists, but unlike lists, they cannot be changed after their creation (i.e., they are
immutable).
•Tuples can hold elements of different data types.
•The main characteristics of tuples are being ordered, heterogeneous and immutable
•A tuple is created by placing all the items inside parentheses (), separated by commas. A tuple can
have any number of items and they can be of different data types.
• Tuples are immutable, faster, hashable, memory-efficient, and ideal for representing fixed,
meaningful data collections.
• Tuples can't be modified, have limited methods, are less flexible for dynamic data, and may
cause harder-to-trace bugs due to immutability.
Examples:
Tuple Assignment
Packing tuples
Packing tuples assigns multiple Python objects to a tuple.
tuple1 = (obj1, obj2, ..., objN)
Each object in tuples has an index and can be accessed using its index. Once an object has been
assigned to a tuple, it cannot be changed, i.e., it is immutable.
Unpacking tuples
Unpacking tuples assigns the objects in a tuple to multiple variables.
(obj1, obj2, ..., objN) = tuple1
During unpacking, the number of variables must be equal to the number of objects in the tuples. If
this is not the case, a ValueError is raised
Examples:
Return Type:
In Python, a function can return a single tuple containing one or more values. Even
when a function appears to return multiple values separated by commas, Python
internally packages these values into a single tuple.
Python’s data structures (like tuples and lists) are composable — meaning:
They can contain other tuples, lists, or any type of Python object.