0% found this document useful (0 votes)
3 views14 pages

Module 4 Notes

The document provides a comprehensive overview of string manipulation in Python, covering concepts such as indexing, slicing, and string methods. It explains how to access individual characters, create substrings, and perform various operations like formatting and transforming strings. Additionally, it highlights the immutability of strings and the importance of creating new strings for modifications.

Uploaded by

Nighat Iqbal
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views14 pages

Module 4 Notes

The document provides a comprehensive overview of string manipulation in Python, covering concepts such as indexing, slicing, and string methods. It explains how to access individual characters, create substrings, and perform various operations like formatting and transforming strings. Additionally, it highlights the immutability of strings and the importance of creating new strings for modifications.

Uploaded by

Nighat Iqbal
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

 Strings are sequences of characters. You can access individual characters using indexing.

 Python uses zero-based indexing, meaning the first character is at index 0.

 You can access characters from the end of a string using negative indexing. The last
character is at index -1.

 String slicing allows you to extract portions of a string. You can specify a start and end index
to create a substring.

To help solidify your understanding, here are some code examples illustrating these concepts:

name = "Jaylen"

print(name[1]) # Output: a

print(name[0]) # Output: J

print(name[5]) # Output: n

text = "Random string with a lot of characters"

print(text[-1]) # Output: s

print(text[-2]) # Output: r

color = "Orange"

print(color[1:4]) # Output: ran

fruit = "Pineapple"

print(fruit[:4]) # Output: Pine

print(fruit[4:]) # Output: apple

 Accessing Individual Characters:

o Python uses zero-based indexing, meaning the first character is at index 0.

o Use square brackets [] with the index to access a specific character.

 For example: my_string[0] accesses the first character of the


string my_string.

o Negative indexing allows access from the end of the string. [-1] represents the last
character, [-2] the second-to-last, and so on.

 Slicing for Substrings:

o Slicing extracts a portion of a string.


o Use the colon : within square brackets to define a range: [start:end].

 The start index is inclusive.

 The end index is exclusive (up to but not including that index).

o Omitting the start defaults to the beginning of the string.

o Omitting the end defaults to the end of the string.

fruit = "Mangosteen"

print(fruit[1:4]) # Output: ang

print(fruit[:5]) # Output: Mango

print(fruit[5:]) # Output: steen

Remember, attempting to access an index outside the string's bounds will result in an IndexError.

we can certainly create new strings based on existing ones.

For example, instead of changing a character at a specific index, we can:

 Slice the parts we want to keep from the original string.

 Concatenate them with the desired modification using the + operator.

Let's illustrate this with a code snippet:

message = "This is a new message"

new_message = message[:2] + "at" + message[5:]

print(new_message)

In this example, we create a new string called new_message by combining a slice of the original
message string , "Th", with the characters "at", and another slice, "is a new message".

You can follow along in the reading as the instructor discusses the code or review the code after
watching the video.

message = "A kong string with a silly typo"

message[2] = "l"

#This will throw an error

message = "A kong string with a silly typo"

new_message = message[0:2] + "l" + message[3:]

print(new_message)
message = "This is a new message"

print(message)

message = "And another one"

print(message)

pets="Cats & Dogs"

[Link]("&")

[Link]("C")

[Link]("Dog")

[Link]("g")

pets="Cats & Dogs"

print([Link]("o"))

#This will throw an error

pets="Cats & Dogs"

"Dragons" in pets

Basic String Methods

In Python, strings are immutable. This means that they can't be modified. So if we wanted to fix a
typo in a string, we can't simply modify the wrong character. We would have to create a new string
with the typo corrected. We can also assign a new value to the variable holding our string.

If we aren't sure what the index of our typo is, we can use the string method index to locate it and
return the index. Let's imagine we have the string "lions tigers and bears" in the variable animals.
We can locate the index that contains the letter g using [Link]("g"), which will return the
index; in this case 8. We can also use substrings to locate the index where the substring begins.
[Link]("bears") would return 17, since that’s the start of the substring. If there’s more than
one match for a substring, the index method will return the first match. If we try to locate a substring
that doesn't exist in the string, we’ll receive a ValueError explaining that the substring was not found.

animals = "lions tigers and bears"

[Link]("g")

animals = "lions tigers and bears"

[Link]("bears")
We can avoid a ValueError by first checking if the substring exists in the string. This can be done using
the in keyword. We saw this keyword earlier when we covered for loops. In this case, it's a
conditional that will be either True or False. If the substring is found in the string, it will be True. If
the substring is not found in the string, it will be False. Using our previous variable animals, we can
do "horses" in animals to check if the substring "horses" is found in our variable. In this case, it
would evaluate to False, since horses aren’t included in our example string. If we did "tigers" in
animals, we'd get True, since this substring is contained in our string.

animals = "lions tigers and bears"

"horses" in animals

animals = "lions tigers and bears"

"tigers" in animals

 Transforming and Formatting:

o upper(): Converts all characters in a string to uppercase.

o lower(): Converts all characters in a string to lowercase.

o strip(): Removes leading and trailing whitespace (spaces, tabs, newlines) from a
string.

o lstrip(): Removes leading whitespace from a string.

o rstrip(): Removes trailing whitespace from a string.

 Getting Information:

o count(): Counts how many times a specific substring appears within a string.

o endswith(): Checks if a string ends with a particular substring.

o isnumeric(): Checks if a string is composed only of numerical characters.

 Joining and Splitting:

o join(): Concatenates strings in a list using a specified separator.

o split(): Splits a string into a list of substrings, using whitespace or a specified


delimiter.
 Formatting with the .format() method:
o You can use curly braces {} as placeholders within a string.
o These placeholders get filled when you call .format() on the string.
o name = "Manny"
o number = len(name) * 3
o print("Hello {}, your lucky number is {}".format(name,
number))
o You can even insert variables in a different order or use them multiple times:
o name = "Manny"
print("Your lucky number is {number},
{name}.".format(name=name, number=len(name)*3))
 Formatting numbers:
o You can control the presentation of numbers, like adding two decimal places for
currency:
o price = 7.5
o with_tax = price * 1.09
print("Base price: ${:.2f}. With Tax: ${:.2f}".format(price,
with_tax))
 Combining formatting with other techniques:
o In this example, we use a loop and string formatting to create a neatly aligned
temperature conversion table:
o def to_celsius(x):
o return (x-32)*5/9
o
o for x in range(0,101,10):
print("{:>3} F | {:>6.2f} C".format(x, to_celsius(x)))

For String References:


[Link]

String Operations
 len(string) - Returns the length of the string. For example:
`python len("abcde") # Output: 5
 for character in string - Iterates over each character in the
string. For example:
 for c in "abcde":
 print(c)
 # Output:
 # a
 # b
 # c
 # d
# e
 if substring in string - Checks whether the substring is part
of the string. For example:
 print("abc" in "abcde") # Output: True
print("def" in "abcde") # Output: False
 string[i] - Accesses the character at index i of the string,
starting at zero. For example:
 print("abcde"[2]) # Output: c
print("abcde"[-1]) # Output: e
 string[i:j] - Accesses the substring starting at index i,
ending at index j minus 1. If i is omitted, its value defaults
to 0. If j is omitted, Python returns everything from i to the
end of the string. For example:
 print("abcde"[0:2]) # Output: ab
print("abcde"[2:]) # Output: cde
String Methods
 [Link]() - Returns a copy of the string with all
lowercase characters. For example:
print("AaBbCcDdEe".lower()) # Output: aabbccddee
 [Link]() - Returns a copy of the string with all
uppercase characters. For example:
print("AaBbCcDdEe".upper()) # Output: AABBCCDDEE
 [Link]() - Returns a copy of the string with the left-
side whitespace removed. For example:
print(" Hello ".lstrip()) # Output: "Hello "
 [Link]() - Returns a copy of the string with the right-
side whitespace removed. For example:
print(" Hello ".rstrip()) # Output: " Hello"
 [Link]() - Returns a copy of the string with both the
left and right-side whitespace removed. For example:
print(" Hello ".strip()) # Output: "Hello"
 [Link](substring)- Returns the number of times substring
is present in the string. For example:
 test = "How much wood would a woodchuck chuck"
print([Link]("wood")) # Output: 2
 [Link]() - Returns True if there are only numeric
characters in the string. If not, returns False. For example:
 print("12345".isnumeric()) # Output: True
print("-123.45".isnumeric()) # Output: False
 [Link]() - Returns True if there are only letters in
the string. If not, returns False. For example:
print("xyzzy".isalpha()) # Output: True
 [Link]() - Returns a list of substrings that were
separated by whitespace (whitespace can be a space, tab, or
new line). For example:
 test = "How much wood would a woodchuck chuck"
print([Link]()) # Output: ['How', 'much', 'wood', 'would', 'a',
'woodchuck', 'chuck']
 [Link](delimiter) - Returns a list of substrings that
were separated by whitespace or another string. For example:
 test = "How-much-wood-would-a-woodchuck-chuck"
print([Link]("-")) # Output: ['How', 'much', 'wood', 'would',
'a', 'woodchuck', 'chuck']
 [Link](old, new) - Returns a new string where all
occurrences of old have been replaced by new. For example:
 test = "How much wood would a woodchuck chuck"
print([Link]("wood", "plastic")) # Output: "How much plastic
would a plasticchuck chuck"
 [Link](list of strings) - Returns a new string with
all the strings joined by the delimiter. For example:
 test = "How much wood would a woodchuck chuck"
print("-".join([Link]())) # Ou

Formatting Strings Reference Guide


 Purpose: Formatting strings makes output easier to read and
understand. This is especially useful when displaying
information like receipts, reports, or anything that needs to
be well-organized.
 Methods:
o format() method: The most common way to format strings in
Python.
 Uses placeholders {} within a string.
 Values are inserted into placeholders using
the format() function.
o name = "Alice"

o age = 30

print("My name is {} and I am {} years old.".format(name, age))


o f-strings (Formatted String Literals): Available in
Python 3.6 and later.
 Concise and readable.
 Placeholders are embedded directly within the
string using curly braces {}.
o name = "Bob"

o age = 25

print(f"My name is {name} and I am {age} years old.")


o Old string formatting (using %): Less common now, but you
might see it in older code.
 Uses % followed by a letter to indicate the data
type (%s for string, %d for integer, etc.).
o name = "Charlie"

o age = 28

print("My name is %s and I am %d years old." % (name, age))


 Formatting Expressions:
o Used within placeholders to control the appearance of the
output.
o Examples:

 {:.2f}: Floating-point number with two decimal


places.
 {:10}: Output is 10 characters wide, right-aligned.
 {:<10}: Output is 10 characters wide, left-aligned.
 {:^10}: Output is 10 characters wide, center-
aligned.
 {:,}: Includes comma separators for thousands.

 Formatting expressions

Expr Meaning Example


{:d} integer value "{0:.0f}".format(10.5) → '10'
{:.2f} floating point with that many decimals '{:.2f}'.format(0.5) → '0.50'
{:.2s} string with that many characters '{:.2s}'.format('Python') → 'Py'
{:<6s} string aligned to the left that many spaces '{:<6s}'.format('Py') → 'Py '
{:>6s} string aligned to the right that many spaces '{:>6s}'.format('Py') → ' Py'
{:^6s} string centered in that many spaces '{:^6s}'.format('Py') → ' Py '

Study Guide: Strings


This study guide provides a quick-reference summary of what you
learned in this lesson and serves as a guide for the upcoming
practice quiz. The string readings in this section are great syntax
guides to help you on the Strings Practice Quiz.
In the Strings segment, you learned about the parts of a string,
string indexing and slicing, creating new strings, string methods
and operations, and formatting strings.
Knowledge
String Operations and Methods
 .format() - String method that can be used to concatenate and
format strings.
o {:.2f} - Within the .format() method, limits a floating
point variable to 2 decimal places. The number of decimal
places can be customized.
 len(string) - String operation that returns the length of the
string.
 string[x] - String operation that accesses the character at
index [x] of the string, where indexing starts at zero.
 string[x:y] - String operation that accesses a substring
starting at index [x] and ending at index [y-1]. If x is
omitted, its value defaults to 0. If y is omitted, the value
will default to len(string).
 [Link](old, new) - String method that returns a new
string where all occurrences of an old substring have been
replaced by a new substring.
 [Link]() - String method that returns a copy of the
string with all lowercase characters.
Coding skills
Skill Group 1
 Use a for loop to iterate through each letter of a string.
 Add a character to the front of a string.
 Add a character to the end of a string.
 Use the .lower() string method to convert the case
(uppercase/lowercase) of the letters within a string variable.
This method is often used to eliminate cases as a factor when
comparing two strings. For example, all lowercase “cat” is not
equal to “Cat” because “Cat” contains an uppercase letter. To
be able to compare the two strings to see if they are the same
word, you can use the .lower() string method to remove
capitalization as a factor in the
# This function accepts a given string and checks each charact
er of
# the string to see if it is a letter or not. If the character is a
# letter, that letter is added to the end of the string variable
# "forwards" and to the beginning of the string variable "backwards"
.
def mirrored_string(my_string):

# Two variables are initialized as string data types using empty


# quotes. The variable "forwards" will hold the "my_string"
# minus any character that is not a letter. The "backwards"
# variable will hold the same letters as "forwards", but in
# in reverse order.
forwards = ""
backwards = ""

# The for loop iterates through each character of the "my_string


"
for character in my_string:

# The if-statement checks if the character is not a space.


if [Link]():

# If True, the body of the loop adds the character to th


e
# to the end of "forwards" and to the front of
# "backwards".
forwards += character
backwards = character + backwards

# If False (meaning the character is not a letter), no actio


n
# is needed. This coding approach results prevents any
# non-alphabetical characters from being written to the
# "forwards" and "backwards" variables. The for loop will
# restart until all characters in "my_string" have been
# processed.
# The final if-statement compares the "forwards" and "backwards"
# strings to see if the letters are the same both forwards and
# backwards. Since Python is case sensitive, the two strings wil
l
# need to be converted to use the same case for this comparison.
if [Link]() == [Link]():
return True
return False
Skill Group 2
 Use the format() method, with {} placeholders for variable
data, to create a new string.
 Use a formatting expression, like {:.2f}, to format a float
variable and configure the number of decimal places to display
for the float.
# This function converts measurement equivalents. Output is formatte
d
# as, "x ounces equals y pounds", with y limited to 2 decimal places
.
def convert_weight(ounces):

# Conversion formula: 1 pound = 16 ounces


pounds = ounces/16

# The result is composed using the .format() method. There are t


wo
# placeholders in the string: the first is for the "ounces"
# variable and the second is for the "pounds" variable. The seco
nd
# placeholder formats the float result of the conversion
# calculation to be limited to 2 decimal places.
result = "{} ounces equals {:.2f} pounds".format(ounces,pounds)
return result
print(convert_weight(12)) # Should be: 12 ounces equals 0.75 pounds
print(convert_weight(50.5)) # Should be: 50.5 ounces equals 3.16 pou
nds
print(convert_weight(16)) # Should be: 16 ounces equals 1.00 pounds
RunReset
Skill Group 3
 Within the format() parameters, select characters at specific
index [ ] positions from a variable string.
 Use the format() method, with {} placeholders for variable
data, to create a new string.
# This function generates a username using the first 3 letters of a
# user’s last name plus their birth year.
def username(last_name, birth_year):

# The .format() method will use the first 3 letters at index


# positions [0,1,2] of the "last_name" variable for the first
# {} placeholder. The second {} placeholder concatenates the use
r’s
# "birth_year" to that string to form a new string username.
return("{}{}".format(last_name[0:3],birth_year))

print(username("Ivanov", "1985"))
# Should display "Iva1985"
print(username("Rodríguez", "2000"))
# Should display "Rod2000"
print(username("Deng", "1991"))
# Should display "Den1991"

Skill Group 4
 Use the .replace() method to replace part of a string.
 Use the len() function to get the number of index positions in
a string.
 Slice a string at a specific index position.
# This function checks a given schedule entry for an old date and, i
f
# found, the function replaces it with a new date.
def replace_date(schedule, old_date, new_date):

# Check if the given "old_date" appears at the end of the given


# string variable "schedule".
if [Link](old_date):

# If True, the body of the if-block will run. The variable "
p" is
# used to hold the slicing index position. The len() functio
n
# is used to measure the length of the string "old_date".
p = len(old_date)

# The "new_schedule" string holds the updated string with th


e
# old date replaced by the new date. The schedule[:-p] part
of
# the code trims the "old_date" substring from "schedule"
# starting at the final index position (or right-side) count
ing
# towards the left the same number of index positions as
# calculated from len(old_date). Then, the code schedule[-
p:]
# starts the indexing position at the slot where the first
# character of the "old_date" used to be positioned. The
# .replace(old_date, new_date) code inserts the "new_date" i
nto
# the position where the "old_date" used to exist.
new_schedule = schedule[:-p] + schedule[-
p:].replace(old_date, new_date)

# Returns the schedule with the new date.


return new_schedule

# If the schedule does not end with the old date, then return th
e
# original sentence without any modifications.
return schedule

print(replace_date("Last year’s annual report will be released in Ma


rch 2023", "2023", "2024"))
# Should display "Last year’s annual report will be released in Marc
h 2024"
print(replace_date("In April, the CEO will hold a conference", "Apri
l", "May"))
# Should display "In April, the CEO will hold a conference"
print(replace_date("The convention is scheduled for October", "Octob
er", "June"))
# Should display "The convention is scheduled for June"

You might also like