Strings
Strings
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"
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)
x = txt.lower()
print(x)
x = txt.upper()
print(x)
Return the number of times the value "apple" appears in the string:
x = txt.count("apple")
print(x)
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:
x = "#".join(myTuple)
print(x)
x = txt.replace("bananas", "apples")
print(x)
x = txt.split()
print(x)
x = txt.startswith("Hello")
print(x)
Make the lower case letters upper case and the upper case letters lower case:
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
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]
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.'
print(greeting.lower())
# Prints: welcome to chili's
print(text.split())
# Prints: ['Silicon', 'Valley']
print(text.split('i'))
# Prints: ['S', 'l', 'con Valley']
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
print(dinosaur.upper())
# Prints: T-REX
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
fruits.clear()
Python Notes for A-Level Computer Science 9618
Copy the fruits list:
x = fruits.copy()
x = fruits.count("cherry")
fruits.extend(cars)
Insert the value "orange" as the second element of the fruit list:
fruits.insert(1, "orange")
fruits.pop(1)
Python Notes for A-Level Computer Science 9618
Remove the "banana" element of the fruit list:
fruits.remove("banana")
fruits.reverse()
cars.sort()
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!
# 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.
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>
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>:
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 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)