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

Strings

This document provides comprehensive notes on Python programming concepts relevant to A-Level Computer Science 9618, including string manipulation, list methods, loops, and key functions. It covers topics such as string indexing, slicing, and methods like .join(), .replace(), and .find(), as well as list operations like append, remove, and sorting. Additionally, it explains control flow with loops, including for and while loops, and introduces concepts like list comprehensions and nested loops.

Uploaded by

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

Strings

This document provides comprehensive notes on Python programming concepts relevant to A-Level Computer Science 9618, including string manipulation, list methods, loops, and key functions. It covers topics such as string indexing, slicing, and methods like .join(), .replace(), and .find(), as well as list operations like append, remove, and sorting. Additionally, it explains control flow with loops, including for and while loops, and introduces concepts like list comprehensions and nested loops.

Uploaded by

Mr Saem
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

Python Notes for A-Level Computer Science 9618

Strings
In computer science, sequences of characters are referred to as strings. Strings
can be any length and can include any character such as letters, numbers,
symbols, and whitespace (spaces, tabs, new lines).

Escaping Characters
Backslashes (\) are used to escape characters in a Python string.

For instance, to print a string with quotation marks, the given code snippet
can be used.
txt = "She said \"Never let go\"."
print(txt) # She said "Never let go".

The in Syntax
The in syntax is used to determine if a letter or a substring exists in a string. It
returns True if a match is found, otherwise False is returned.
game = "Popular Nintendo Game: Mario Kart"

print("l" in game) # Prints: True


print("x" in game) # Prints: False

Indexing and Slicing Strings


Python strings can be indexed using the same notation as lists, since strings
are lists of characters. A single character can be accessed with bracket
notation ([index]), or a substring can be accessed using slicing ([start:end]).

Indexing with negative numbers counts from the end of the string.
str = 'yellow'
str[1] # => 'e'
str[-1] # => 'w'
str[4:6] # => 'ow'
str[:4] # => 'yell'
str[-3:] # => 'low'
Python Notes for A-Level Computer Science 9618
txt = "hello, and welcome to my world."

x = txt.capitalize()

print (x)

txt = "Hello my FRIENDS"

x = txt.lower()

print(x)

txt = "Hello my friends"

x = txt.upper()

print(x)

Return the number of times the value "apple" appears in the string:

txt = "I love apples, apple are my favorite fruit"

x = txt.count("apple")

print(x)

Where in the text is the word "welcome"?:

txt = "Hello, welcome to my world."

x = txt.find("welcome")

print(x)
Python Notes for A-Level Computer Science 9618
Join all items in a tuple into a string, using a hash character as separator:

myTuple = ("John", "Peter", "Vicky")

x = "#".join(myTuple)

print(x)

Replace the word "bananas":

txt = "I like bananas"

x = txt.replace("bananas", "apples")

print(x)

Split a string into a list where each word is a list item:

txt = "welcome to the jungle"

x = txt.split()

print(x)

Check if the string starts with "Hello":

txt = "Hello, welcome to my world."

x = txt.startswith("Hello")

print(x)

Make the lower case letters upper case and the upper case letters lower case:

txt = "Hello My Name Is PETER"

x = txt.swapcase()

print(x)
Python Notes for A-Level Computer Science 9618
Iterate String
To iterate through a string in Python, “for…in” notation is used.
str = "hello"
for c in str:
print(c)

# h
# e
# l
# l
# o

Built-in Function len()


In Python, the built-in len() function can be used to determine the length of
an object. It can be used to compute the length of strings, lists, sets, and other
countable objects.
length = len("Hello")
print(length)
# Output: 5

colors = ['red', 'yellow', 'green']


print(len(colors))
# Output: 3

String Concatenation
To combine the content of two strings into a single string, Python provides
the + operator. This process of joining strings is called concatenation.
x = 'One fish, '
y = 'two fish.'

z = x + y

print(z)
# Output: One fish, two fish.
Python Notes for A-Level Computer Science 9618
Immutable strings
Strings are immutable in Python. This means that once a string has been
defined, it can’t be changed.

There are no mutating methods for strings. This is unlike data types like lists,
which can be modified once they are created.

IndexError
When indexing into a string in Python, if you try to access an index that
doesn’t exist, an IndexError is generated. For example, the following code
would create an IndexError:
fruit = "Berry"
indx = fruit[6]

Python String .format()


The Python string method .format() replaces empty brace ({}) placeholders in
the string with its arguments.

If keywords are specified within the placeholders, they are replaced with the
corresponding named arguments to the method.
msg1 = 'Fred scored {} out of {} points.'
msg1.format(3, 10)
# => 'Fred scored 3 out of 10 points.'

msg2 = 'Fred {verb} a {adjective} {noun}.'


msg2.format(adjective='fluffy', verb='tickled', noun='hamster')
# => 'Fred tickled a fluffy hamster.'

String Method .lower()


The string method .lower() returns a string with all uppercase characters
converted into lowercase.
Python Notes for A-Level Computer Science 9618
greeting = "Welcome To Chili's"

print(greeting.lower())
# Prints: welcome to chili's

String Method .strip()


The string method .strip() can be used to remove characters from the
beginning and end of a string.

A string argument can be passed to the method, specifying the set of


characters to be stripped. With no arguments to the method, whitespace is
removed.
text1 = ' apples and oranges '
text1.strip() # => 'apples and oranges'

text2 = '...+...lemons and limes...-...'

# Here we strip just the "." characters


text2.strip('.') # => '+...lemons and limes...-'

# Here we strip both "." and "+" characters


text2.strip('.+') # => 'lemons and limes...-'

# Here we strip ".", "+", and "-" characters


text2.strip('.+-') # => 'lemons and limes'

String Method .title()


The string method .title() returns the string in title case. With title case, the
first character of each word is capitalized while the rest of the characters are
lowercase.
my_var = "dark knight"
print(my_var.title())

# Prints: Dark Knight

String Method .split()


Python Notes for A-Level Computer Science 9618
The string method .split() splits a string into a list of items:

• If no argument is passed, the default behavior is to split on whitespace.


• If an argument is passed to the method, that value is used as the
delimiter on which to split the string.

text = "Silicon Valley"

print(text.split())
# Prints: ['Silicon', 'Valley']

print(text.split('i'))
# Prints: ['S', 'l', 'con Valley']

Python string method .find()


The Python string method .find() returns the index of the first occurrence of
the string passed as the argument. It returns -1 if no occurrence is found.
mountain_name = "Mount Kilimanjaro"
print(mountain_name.find("o")) # Prints 1 in the console.

String replace
The .replace() method is used to replace the occurence of the first argument
with the second argument within the string.

The first argument is the old substring to be replaced, and the second
argument is the new substring that will replace every occurence of the first
one within the string.
fruit = "Strawberry"
print(fruit.replace('r', 'R'))

# StRawbeRRy

String Method .upper()


The string method .upper() returns the string with all lowercase characters
converted to uppercase.
Python Notes for A-Level Computer Science 9618
dinosaur = "T-Rex"

print(dinosaur.upper())
# Prints: T-REX

String Method .join()


The string method .join() concatenates a list of strings together to create a
new string joined with the desired delimiter.

The .join() method is run on the delimiter and the array of strings to be
concatenated together is passed in as an argument.
x = "-".join(["Codecademy", "is", "awesome"])

print(x)
# Prints: Codecademy-is-awesome

Python List/Array Methods


Add an element to the fruits list:

fruits = ['apple', 'banana', 'cherry']


fruits.append("orange")

Remove all elements from the fruits list:

fruits = ['apple', 'banana', 'cherry', 'orange']

fruits.clear()
Python Notes for A-Level Computer Science 9618
Copy the fruits list:

fruits = ['apple', 'banana', 'cherry', 'orange']

x = fruits.copy()

Return the number of times the value "cherry" appears int


the fruits list:

fruits = ['apple', 'banana', 'cherry']

x = fruits.count("cherry")

Add the elements of cars to the fruits list:

fruits = ['apple', 'banana', 'cherry']

cars = ['Ford', 'BMW', 'Volvo']

fruits.extend(cars)

Insert the value "orange" as the second element of the fruit list:

fruits = ['apple', 'banana', 'cherry']

fruits.insert(1, "orange")

Remove the second element of the fruit list:

fruits = ['apple', 'banana', 'cherry']

fruits.pop(1)
Python Notes for A-Level Computer Science 9618
Remove the "banana" element of the fruit list:

fruits = ['apple', 'banana', 'cherry']

fruits.remove("banana")

Reverse the order of the fruit list:

fruits = ['apple', 'banana', 'cherry']

fruits.reverse()

Sort the list alphabetically:

cars = ['Ford', 'BMW', 'Volvo']

cars.sort()

What is the position of the value "cherry":

fruits = ['apple', 'banana', 'cherry']

x = fruits.index("cherry")

Loops

break Keyword
In a loop, the break keyword escapes the loop, regardless of the iteration
number. Once break executes, the program will continue to execute after the
loop.
Python Notes for A-Level Computer Science 9618
In this example, the output would be:

• 0
• 254
• 2
• Negative number detected!

numbers = [0, 254, 2, -1, 3]

for num in numbers:


if (num < 0):
print("Negative number detected!")
break
print(num)

# 0
# 254
# 2
# Negative number detected!
Python List Comprehension
Python list comprehensions provide a concise way for creating lists. It consists
of brackets containing an expression followed by a for clause, then zero or
more for or if clauses: [EXPRESSION for ITEM in LIST <if CONDITIONAL>] .

The expressions can be anything - any kind of object can go into a list.

A list comprehension always returns a list.


# List comprehension for the squares of all even numbers
between 0 and 9
result = [x**2 for x in range(10) if x % 2 == 0]

print(result)
# [0, 4, 16, 36, 64]
Python For Loop
A Python for loop can be used to iterate over a list of items and perform a set
of actions on each item. The syntax of a for loop consists of assigning a
temporary value to a variable on each successive iteration.
Python Notes for A-Level Computer Science 9618
When writing a for loop, remember to properly indent each action, otherwise
an IndentationError will result.
for <temporary variable> in <list variable>:
<action statement>
<action statement>

#each num in nums will be printed below


nums = [1,2,3,4,5]
for num in nums:
print(num)
The Python continue Keyword
In Python, the continue keyword is used inside a loop to skip the remaining
code inside the loop code block and begin the next loop iteration.
big_number_list = [1, 2, -1, 4, -5, 5, 2, -9]

# Print only positive numbers:


for i in big_number_list:
if i < 0:
continue
print(i)
Python for Loops
Python for loops can be used to iterate over and perform an action one time
for each element in a list.

Proper for loop syntax assigns a temporary value, the current item of the list,
to a variable on each successive iteration: for <temporary value> in <a list>:

forloop bodies must be indented to avoid an IndentationError.


dog_breeds = ["boxer", "bulldog", "shiba inu"]

# Print each breed:


for breed in dog_breeds:
print(breed)
Python Loops with range().
In Python, a for loop can be used to perform an action a specific number of
times in a row.
Python Notes for A-Level Computer Science 9618
The range() function can be used to create a list that can be used to specify the
number of iterations in a for loop.
# Print the numbers 0, 1, 2:
for i in range(3):
print(i)

# Print "WARNING" 3 times:


for i in range(3):
print("WARNING")
Infinite Loop
An infinite loop is a loop that never terminates. Infinite loops result when the
conditions of the loop prevent it from terminating. This could be due to a typo
in the conditional statement within the loop or incorrect logic. To interrupt a
Python program that is running forever, press the Ctrl and C keys together on
your keyboard.
Python while Loops
In Python, a while loop will repeatedly execute a code block as long as a
condition evaluates to True.

The condition of a while loop is always checked first before the block of code
runs. If the condition is not met initially, then the code block will never run.
# This loop will only run 1 time
hungry = True
while hungry:
print("Time to eat!")
hungry = False

# This loop will run 5 times


i = 1
while i < 6:
print(i)
i = i + 1
Python Nested Loops
In Python, loops can be nested inside other loops. Nested loops can be used
to access items of lists which are inside other lists. The item selected from the
outer loop can be used as the list for the inner loop to iterate over.
Python Notes for A-Level Computer Science 9618
groups = [["Jobs", "Gates"], ["Newton", "Euclid"], ["Einstein",
"Feynman"]]

# This outer loop will iterate over each list in the groups
list
for group in groups:
# This inner loop will go through each name in each list
for name in group:
print(name)

You might also like