100218- Python
Programming
Module 3: Strings
➢ Creating and Storing Strings:
• String: In Python, strings are sequences of characters used to represent text. They are
created by enclosing characters within quotes and are stored in variables.
• Creating Strings:
1. Single or Double Quotes: The most common way to create a string is to enclose
characters within either single quotes (') or double quotes ("). Python treats both
interchangeably.
my_string_single = 'Hello, Python!’
my_string_double = "Hello, Python!“
2. Triple Quotes (Multi-line Strings): For strings that span multiple lines, or for
docstrings (documentation strings), triple single quotes (''') or triple double quotes
(""") are used.
multi_line_string = '''This is a
multi-line string in
Python.’‘’
docstring_example = """This is a docstring
that explains a function or module.""“
3. Strings with Embedded Quotes: To include single quotes within a string enclosed by
single quotes, or double quotes within a string enclosed by double quotes, use the
backslash (`\`) as an escape character. Alternatively, use the opposite type of quote
to enclose the string.
escaped_quote = 'She said, "It\'s amazing!“’
opposite_quote = "He said, 'Hello!'"
➢ Creating and Storing Strings:
• Storing Strings: Once created, strings are typically stored in
variables using the assignment operator (=).
my_variable = "This is a string stored in a variable."
• Key Characteristics of Python Strings:
1. Immutability: Strings in Python are immutable, meaning their content
cannot be changed after creation. Any operation that appears to modify a
string actually creates a new string with the desired changes.
2. Sequences: Strings are sequences, allowing individual characters to be
accessed using indexing (e.g., my_string[0]) and substrings to be extracted
using slicing (e.g., my_string[0:5]).
➢ Basic String Operations:
• Python provides various basic operations and methods for
manipulating strings. Here are some fundamental examples:
1. String Creation: Strings can be created using single, double, or
triple quotes.
my_string_single = 'Hello'
my_string_double = "World"
my_string_triple = """This is a
multiline string."""
2. Concatenation: Strings can be combined using the + operator.
greeting = "Hello" + " " + "Python"
# Result: "Hello Python"
3. Repetition: Strings can be repeated using the * operator.
repeated_string = "abc" * 3
Result: "abcabcabc"
➢ Basic String Operations:
4. Length: The len() function returns the number of characters in a string.
length = len("Python")
# Result: 6
5. Indexing and Slicing: Characters can be accessed by their index (starting
from 0). Substrings can be extracted using slicing.
my_string = "Programming"
first_char = my_string[0] # 'P'
substring = my_string[3:7] # 'gram'
6. Case Conversion: Methods like upper(), lower(), capitalize(), and title()
modify the case of characters.
text = "Python is Fun"
uppercase_text = [Link]() # "PYTHON IS FUN"
lowercase_text = [Link]() # "python is fun"
7. Stripping Whitespace: The strip(), lstrip(), and rstrip() methods remove
leading/trailing whitespace.
padded_string = " hello "
stripped_string = padded_string.strip() # "hello"
➢ Basic String Operations:
8. Replacing Substrings: The replace() method substitutes
occurrences of a substring.
sentence = "I like apples."
new_sentence = [Link]("apples", "oranges")
# "I like oranges."
9. Splitting and Joining: The split() method divides a string into a
list of substrings, and join() concatenates elements of an
iterable into a string.
words = "Python is powerful".split(" ") # ['Python', 'is', 'powerful']
rejoined_string = "-".join(words) # "Python-is-powerful"
[Link]: The find() and index() methods locate the first
occurrence of a substring. find() returns -1 if not found, while
index() raises a ValueError.
data = "Hello World"
pos_find = [Link]("World") # 6
pos_index = [Link]("World") # 6
➢ Accessing Characters in String by Index Number:
• In Python, individual characters within a string can be accessed using indexing. Strings
are ordered sequences, and each character is assigned a numerical index.
1. Positive Indexing:
• Python uses zero-based indexing, meaning the first character is at index 0, the second at 1, and so on.
• To access a character, use square brackets [] after the string variable, enclosing the desired index.
my_string = "Python"
first_char = my_string[0] # Accesses 'P'
third_char = my_string[2] # Accesses 't'
2. Negative Indexing:
• Negative indices allow access to characters from the end of the string.
• -1 refers to the last character, -2 to the second-to-last, and so on.
my_string = "Python"
last_char = my_string[-1] # Accesses 'n'
second_last_char = my_string[-2] # Accesses 'o’
• Important Points Regarding String:
1. Attempting to access an index that is out of the valid range (e.g., an index greater than or equal to the
string's length for positive indexing, or a negative index that goes beyond the string's start) will result in an
IndexError.
2. Strings in Python are immutable, meaning you cannot change individual characters within a string directly
by assigning a new value to an index. You would need to create a new string with the desired modifications.
➢ String Slicing and Joining:
• String Slicing in Python: String slicing in Python allows extraction of a
portion of a string, creating a new substring. This is achieved using square
brackets [] with a colon : inside, specifying a range of indices.
▪ Syntax: string[start:end:step]
o start: The index where the slice begins (inclusive). If omitted, it defaults to 0 (beginning of the
string).
o end: The index where the slice ends (exclusive). If omitted, it defaults to the length of the string
(end of the string).
o step: The increment between characters in the slice. If omitted, it defaults to 1. A negative step
value reverses the string and can be used for slicing in reverse.
▪ Examples:
my_string = "Hello, Python!"
print(my_string[0:5]) # Output: Hello (characters from index 0 up to, but not including, 5)
print(my_string[7:]) # Output: Python! (characters from index 7 to the end)
print(my_string[:5]) # Output: Hello (characters from the beginning up to, but not including, 5)
print(my_string[::2]) # Output: Hlo yhn (every second character)
print(my_string[::-1]) # Output: !nohtyP ,olleH (reversed string)
➢ String Slicing and Joining:
• String Joining in Python: String joining in Python concatenates elements of an
iterable (like a list or tuple of strings) into a single string, using a specified
separator.
▪ Syntax: [Link](iterable)
o separator: The string that will be inserted between each element of the iterable during joining.
o iterable: An iterable containing string elements to be joined.
▪ Examples:
words = ["Hello", "World", "from", "Python"]
separator_space = " "
joined_string_space = separator_space.join(words)
print(joined_string_space) # Output: Hello World from Python
separator_dash = "-"
joined_string_dash = separator_dash.join(words)
print(joined_string_dash) # Output: Hello-World-from-Python
empty_separator = ""
joined_string_concat = empty_separator.join(["A", "B", "C"])
print(joined_string_concat) # Output: ABC
➢ String Methods:
• Python string methods are built-in functions that can be called on string objects
to perform various operations and manipulations. These methods allow for
efficient handling of text data without the need to write custom functions for
common tasks.
• Common Categories of String Methods:
1. Case Conversion:
• upper(): Converts all characters in the string to uppercase.
• lower(): Converts all characters in the string to lowercase.
• capitalize(): Capitalizes the first character of the string and converts the rest to lowercase.
• title(): Converts the first character of each word to uppercase and the rest to lowercase.
• casefold(): Converts the string to casefolded form, which is more aggressive than lower() for
case-insensitive comparisons.
2. Searching and Finding:
• find(substring): Returns the lowest index of the substring if found, otherwise returns -1.
• index(substring): Similar to find(), but raises a ValueError if the substring is not found.
• count(substring): Returns the number of occurrences of the substring in the string.
• startswith(prefix): Checks if the string starts with the specified prefix.
• endswith(suffix): Checks if the string ends with the specified suffix.
➢ String Methods:
3. Modification and Replacement:
• replace(old, new): Replaces all occurrences of old with new.
• strip(): Removes leading and trailing whitespace (or specified characters).
• lstrip(): Removes leading whitespace (or specified characters).
• rstrip(): Removes trailing whitespace (or specified characters).
• join(iterable): Concatenates elements of an iterable (e.g., list of strings) with the string as a
separator.
4. Splitting and Partitioning:
• split(separator): Splits the string into a list of substrings based on the specified separator.
• splitlines(): Splits the string into a list of lines.
• partition(separator): Splits the string into a 3-tuple containing the part before the
separator, the separator itself, and the part after the separator.
5. Formatting:
• format(): Formats the string using placeholders.
• center(width, fillchar): Centers the string within a specified width, padding with a fill
character.
• ljust(width, fillchar): Left-justifies the string within a specified width.
• rjust(width, fillchar): Right-justifies the string within a specified width.
➢ String Methods:
• Example:
my_string = " Hello, Python! "
# Case conversion
print(my_string.upper())
print(my_string.lower())
# Stripping whitespace
cleaned_string = my_string.strip()
print(cleaned_string)
# Replacing characters
modified_string = cleaned_string.replace("Python", "World")
print(modified_string)
# Splitting the string
words = modified_string.split(", ")
print(words)
➢ Formatting Strings:
• Python provides several methods for formatting strings, allowing for the
dynamic insertion of values and control over their presentation. The
primary methods include:
1. f-strings (Formatted String Literals): Introduced in Python 3.6, f-strings
are the recommended and most modern approach. They are prefixed
with an f or F and allow embedding expressions directly within curly
braces {} inside the string literal.
1. name = "Alice"
2. age = 30
3. message = f"Hello, {name}! You are {age} years old."
4. print(message)
2. [Link]() Method: This method, available on string objects, uses
curly braces {} as placeholders within a template string. Values are then
passed as arguments to the .format() method, either positionally or by
keyword.
1. item = "apple"
2. price = 1.25
3. message = "The {} costs ${:.2f}.".format(item, price)
4. print(message)
➢ Formatting Strings:
3. % Operator (Old-style String Formatting): This is the original method
for string formatting in Python, similar to C's printf(). It uses the %
operator with format specifiers like %s (for strings), %d (for integers),
and %f (for floats).
city = "New York"
population = 8000000
message = "{} has a population of %d.".format(city) % population
print(message)
• Choosing a Method:
1. f-strings are generally preferred for their readability, conciseness, and
performance.
2. The [Link]() method offers good flexibility and is a suitable
alternative, especially in older Python versions or when explicit
positional/keyword arguments are desired.
3. The % operator is considered legacy and is less commonly used in
modern Python code, though it may be encountered in older projects.