"Strings hold characters, loops repeat actions. That's coding in a nutshell."
- Strings in the PC memory (encodings, ascii/unicode),
ord()
,chr()
- Slicing
- Methods of Strings
- Introduction to loops
- Quiz
- Homework
We have already worked with strings a lot, but really, how does it work under the hood?
Strings in a computer's memory are stored as sequences of bytes
. To represent strings of text, a computer has a system that maps these byte sequences
to characters
. This system is called a character encoding.
Two common character encoding systems are ASCII
and Unicode
:
It uses 7 bits
to represent 128 unique characters
, which includes letters, numbers, and control characters.
NOTE: ASCII is limited to English characters and does not support international text.
It is a comprehensive encoding system
designed to represent text in most of the world's writing systems. Unlike ASCII, Unicode uses a variable-length encoding system, which can be 8
, 16
, or 32
bits long.
NOTE: This encoding allows to represent over a million unique characters.
Python
provides two functions to interact with character encodings:
-
ord(c)
: Given a string representing one Unicode character,ord()
returns an integer representing theUnicode
code point of that character. For example,ord('a')
returns the integer97
. -
chr()
Given an integer representing aUnicode
code point,chr()
returns a string representing the character.
NOTE: This is not used in the production environments, but we will a have a homework based on this material, so get acquainted.
print(ord('a'))
print(chr('97'))
97
a
These functions allow us to convert between a character's byte
and its str
representations.
It will be very helpful once we start working with files later.
Python
provides several ways to format strings. Two common methods are raw strings
and formatted string literals
.
Raw strings are useful when you need to use lots of backslashes, like defining a file path on Windows
/Linux
/Mac OS
. In a raw string, backslashes are treated as literal characters and not as escape characters, but as a part of the string.
path = r"C:\Users\Name\Documents\file.txt"
print(path)
C:\Users\Name\Documents\file.txt
Formatted string literals, or f strings
, are a way to embed expressions inside string literals using curly braces {}
. They are concise and easy to use for embedding variables and expressions within a string.
It really simplifies life using them, just compare two print()
statements shown in the example below:
name = "Alice"
age = 25
# Without ``f`` strings
print("Hello, ", name, ".", "You are ", age, "years old.")
# With ``f`` strings
greeting = f"Hello, {name}. You are {age} years old."
print(greeting)
Hello, Alice. You are 25 years old.
Slicing is a mechanism in Python
which allows you to extract a part of a string, also known as a substring.
A slice is created by specifying two indices in square brackets, separated by a colon [start:stop]
where start
is the index where the slice starts and stop
is the index where the slice ends.
NOTE: The start index is included in the slice, but the stop index is not.
You can also include a 3rd parameter, step
, which lets you skip characters within the slice [start:stop:step]
.
Let's take a look closer on the table below:
Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
---|---|---|---|---|---|---|---|---|---|---|
Char | a | b | c | d | e | f | g | h | i | j |
Index | -10 | -9 | -8 | -7 | -6 | -5 | -4 | -3 | -2 | -1 |
We can ommit some inidces, and the count will be started from the start
/end
s = "abcdefghij"
print(s[1:5]) # Extracts from index 1 to 4
print(s[:5]) # Extracts from the beginning to index 4
print(s[7:]) # Extracts from index 7 to the end
print(s[:]) # Extracts the whole string
print(s[::2]) # Extracts every second character from the string
print(s[::-1]) # Reverses the string
bcde
abcde
hij
abcdefghij
acegi
jihgfedcba
NOTE: Python also supports negative
indices in slicing, which counts from the end of the string backwards
s = "abcdefghij"
print(s[-4:-1]) # Extracts from the fourth-last to the second-last character
print(s[:-5]) # Extracts from the beginning to the fifth-last character
print(s[-3:]) # Extracts the last three characters
print(s[::-2]) # Extracts every second character from the string in reverse
ghi
abcde
hij
jhfdb
There will be only 2 assigments in this section, but they are a little bit tricky, good luck!
Objective: Write a program that takes a string as input and returns it in reverse order using slicing.
# Sample Input: 'Python'
# Sample Output: 'nohtyP'
Objective: Develop a program that checks whether a word is a palindrome (reads the same backward as forward).
Input: The user inputs a word.
Output: The program states whether it is a palindrome.
Example:
Input: radar / level
Output:
This word is a palindrome.
In this section we will find out the real power of strings in Python
.
In Python, functions and methods both refer to blocks of code that perform tasks. The key difference between them lies in how they are used and invoked within the code.
A function is a standalone unit of code that performs a specific task. It can be called directly by its name and can work on different types of data. Functions can take inputs (arguments) and return outputs (results).
name = "Hello"
print(len(result)) # len() --> function
A method is similar to a function, but it is associated with an object and is called on that object using dot(.)
notation.
name = "hello"
print(result.capitalize()) # capitalize() --> method
You have to understand the following key points:
- Functions are called by name and can be used independently of objects.
- Methods are called on objects and often work with the data within those objects.
The dir()
function will list all the attributes of any object in Python
.
print(dir(str))
['__add__', '__class__', '__contains__', ... 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', ...]
The help()
function can be used to understand what a particular method does.
help(str.capitalize)
Help on method_descriptor:
capitalize(self, /)
Return a capitalized version of the string.
More specifically, make the first character have upper case and the rest lower
case.
These outputs will provide detailed information about the methods, which can be very helpful when you're trying to figure out how to use a particular string method or which method can be used on the object.
Note: Don't forget to refer to the official documentation for Python
Method | Description | Example | Output |
---|---|---|---|
capitalize() |
Capitalizes the first letter of the string. | 'hello'.capitalize() |
'Hello' |
casefold() |
Converts string to lower case for caseless matching. | 'HELLO'.casefold() |
'hello' |
center(width) |
Centers the string within a specified width. | 'hello'.center(10) |
' hello ' |
count(sub) |
Returns the number of occurrences of a substring. | 'hello'.count('l') |
2 |
endswith(suffix) |
Checks if the string ends with the specified suffix. | 'hello'.endswith('o') |
True |
find(sub) |
Searches the string for a specified substring and returns the index. | 'hello'.find('e') |
1 |
format(*args) |
Formats the string into a nicer output. | '{} world'.format('hello') |
'hello world' |
replace(old, new) |
Replaces occurrences of a substring with another. | 'hello'.replace('e', 'a') |
'hallo' |
strip(chars) |
Trims leading and trailing characters (whitespace by default). | ' hello '.strip() |
'hello' |
upper() |
Converts all characters of the string to uppercase. | 'hello'.upper() |
'HELLO' |
Methods below are used tightly with a list
data structure, which we will learn during next lessons. We will take a closer look on them later, just bear in mind that they exist!
Method | Description | Example | Output |
---|---|---|---|
join(iterable) |
Joins the elements of an iterable by the string. | '-'.join(['1', '2']) |
'1-2' |
split(sep) |
Splits the string at the specified separator. | '1,2,3'.split(',') |
['1', '2', '3'] |
Objective: Create a program that takes a user's name and ensures the first letter is capitalized and the rest are lowercase, regardless of how the user enters it.
Input: aLiCe # Note, that you might want to use 2 methods to achieve the expected output
Output: Alice
Objective: Write a script that counts the number of times a substring appears in a given string.
Input:
Enter the main string: hellohellohello
Enter the substring to count: ello
Output: The substring 'ello' appears 3 times in 'hellohellohello'.
Objective: Ask the user to enter a sentence and then display it centered within a frame
of a specified width.
Input:
Enter your sentence: hello
Set the frame width: 4
Output:
hello
Objective: Create a program that can convert a given string into either uppercase
or lowercase
based on the user's choice.
Input:
Enter your text: Python is Fun!
Choose 'upper' or 'lower': upper
Output: PYTHON IS FUN!
Objective: Write a program that ensures all URLs entered by a user start with https://
. If it doesn't, add it to the beginning.
Input: Enter the URL: www.swetrix.com
Output: Corrected URL: https://www.swetrix.com
Loops
are a powerful feature of computers, giving them the ability to perform repetitive tasks.
Python
provides two primary types of loops:
- Counting Loops (
for
): Ideal for situations where the number of iterations is known in advance. - Conditional Loops (
while
): These loopscontinue
to execute until a certain condition is met.
for variable_name in range(number_of_iterations):
code_block
# Note that we need to use indentation for this construction
for i in range(10):
print("Hello")
# 10 times
Hello
Hello
...
Hello
The purpose and function of the loop variable
_may not be immediately obvious. Let's look at an example to clarify
for i in range(10):
print(i)
When the loop starts, Python
assigns the initial value of the loop variable i to 0
.
With each iteration of the loop body, it increments the value of i by 1
.
0
1
2
3
4
5
6
7
8
9
The diagram shows how for
loop
works in Python
.
graph TD
A[Start] --> B[Initialize Loop Variable]
B --> C{Condition Check}
C -- True --> D[Execute Loop Body]
D --> E[Increment Loop Variable]
E --> C
C -- False --> F[End]
Variable names for loops should be:
- Meaningful and descriptive
- Shorter names are common as well. Generally, programmers use the letters
i
,j
,k
for loop variables.
# Common use
for i in range(10): # j, k , etc..
print(i)
# Meaningful and descriptive
for number in range(10):
print(number)
It is important you understand that the main goal is to make code understandable for people you are working with.
The range()
function in Python
is used to generate a sequence of numbers. It is often used with the for
loop to iterate over a sequence of numbers as you could see from the examples above.
To be more precise, we can say that the range(n)
function generates a sequence of numbers from 0 to n-1
, and the for loop iterates through this sequence.
print(range(10))
range(0, 10)
The range()
function in Python can take up to three parameters: range(start, stop, step)
. Here's what each parameter represents:
start
: The beginning of the sequence.stop
: The end of the sequence (exclusive -->(stop-1)
).step
: The increment between each number in the sequence.
Function Call | Description | Generated Sequence |
---|---|---|
range(1, 10, 2) |
Starts at 1, ends before 10, steps by 2 | 1, 3, 5, 7, 9 |
range(5, 30, 5) |
Starts at 5, ends before 30, steps by 5 | 5, 10, 15, 20, 25 |
range(10, 1, -1) |
Starts at 10, ends before 1, steps by -1 | 10, 9, 8, 7, 6, 5, 4, 3, 2 |
range(20, 10, -2) |
Starts at 20, ends before 10, steps by -2 | 20, 18, 16, 14, 12 |
range(3, 8, 1) |
Starts at 3, ends before 8, steps by 1 | 3, 4, 5, 6, 7 |
range(0, -10, -1) |
Starts at 0, ends before -10, steps by -1 | 0, -1, -2, -3, -4, -5, -6, -7, -8, -9 |
There are two different ways to iterate through objects in python ->
for variable in ..
and for variable in range()
The for in
loop is used to iterate over elements of a sequence, such as a str
, list
, string
, tuple
, or any iterable object
which you will learn during the next lessons.
This type of loop goes through each item in the sequence, one by one.
for element in iterable:
# Do something with element
s = 'Python'
for char in s:
print(char) # Directly accessing the elemenet
We can iterate through the string using the following construction and len()
function
s = 'Python'
for index in range(len(s)):
print(s[i]) # Accessing the element of the string using indexing
P
y
t
h
o
n
Use for in
when you have an iterable (like a list
or string
) and you want to perform actions on each element.
Use for in range()
when you need to repeat actions a specific number of times, or when you need to iterate using a counter.
# Don't forget that we can pas 1-3 arguments into the `range()` function
for i in range(2, 10, 2):
print(i)
Objective: Imagine that you are defusing a bomb which will explode in n
seconds.
- The program starts with a countdown from a given number
n
to1
. - When the countdown reaches
1
, prompt the user to choose a wire to cut:red
orblue
. - If the user chooses
red
-> the bomb explodes. - If the user chooses
blue
-> the bomb is defused. - Make the application very interactive.
Input:
Enter the countdown time: 5
Output:
The bomb will explode in 5 seconds!
5
4
3
2
1
Quick! Which wire to cut? Red or Blue?
User Input: Blue
Output:
You cut the blue wire...
The bomb has been defused. Congratulations, you saved the day!
# Alternatively
User Input: Red
Output:
You cut the red wire...
BOOM!!! The bomb exploded
Objective: Write a program that generates the Fibonacci sequence up to a user-defined number.
Fibonacci Sequence Example: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89,…
Input: The user enters a number `n`.
Output: The program outputs the first `n` numbers of the Fibonacci sequence.
Example:
Input: 5
Output: 0, 1, 1, 2, 3
Objective: Create a script that prints the multiplication table for a number provided by the user.
Input: The user inputs a number.
Output: The program prints the multiplication table for that number.
Example:
Input: 3
Output:
3 x 1 = 3
3 x 2 = 6
3 x 3 = 9
...
3 x 10 = 30
Which function returns the Unicode code point for a single character?
A) chr()
B) ord()
C) len()
D) str()
What does the following string slicing return?
s = 'HelloWorld'; print(s[2:7])
A) Hello
B) World
C) lloWo
D) HelloWorld
Which of the following is the correct way to iterate through the string
"Python"
using a for loop?
A) for i in 'Python': print(i)
B) for i in range('Python'): print(i)
C) for i in len('Python'): print(i)
D) for 'Python': print(i)
Which statement about
raw
strings in Python is true?
A) They treat backslashes as escape characters.
B) They cannot contain special characters.
C) They treat backslashes as normal characters.
D) They start with the letter f
instead of r
.
What will be the output of the following code?
x = "awesome"
print(f"Python is {x}")
A) Python is x
B) Python is awesome
C) Python is {awesome}
D) x is awesome
What is the result of the following?
print("Hello, World!".find("W"))
A) 6
B) 7
C) Hello
D) -1
How do you print numbers from 1 to 5 using a for loop in Python?
A)
for i in range(1, 6):
print(i)
B)
for i in range(5):
print(i)
C)
for i in 1 to 5:
print(i)
D)
for i in range(6):
print(i)
What does the following code return?
print("PYTHON".casefold())
A) PYTHON
B) python
C) An error
D) PYthON
Objective: Develop an application that can encrypt and decrypt multiple messages using ASCII and Unicode code points.
The program should allow the user to choose between encryption and decryption and specify the number of messages.
# Example of how the program should work
# Menu:
# 1. Encrypt Messages
# 2. Decrypt Messages
# Encrypt Input:
Enter the number of messages to encrypt: 2
Enter message 1: Hello
Enter message 2: World
# Encrypt Output:
Encrypted Message 1: 72 101 108 108 111
Encrypted Message 2: 87 111 114 108 100
# Decrypt Input:
Enter the number of messages to decrypt: 2
Enter message 1: 72 101 108 108 111
Enter message 2: 87 111 114 108 100
# Decrypt Output:
Decrypted Message 1: Hello
Decrypted Message 2: World
Objective: Develop a program that allows users to input a string and then perform various slicing operations based on the user input. Ask if the user wants to add a step
and process the request accordingly
Input:
Enter a string: Hello World
Enter start index: 2
Enter stop index: 8
Do you want to add a step (yes/no)? yes
Enter step: 2
Output:
The sliced string with step is: l o
Objective: Write a program that builds a story based on the user's choices. Use f
strings for dynamic storytelling.
Input:
Choose your character's name: Alice
Choose a companion (dog/cat): dog
Choose a destination (forest/beach): forest
Output:
Alice, along with her loyal dog, set out on an adventure to the forest. [Continue the story...]
# Be creative! You can add more variables and sentences to the story!
Objective:: Develop a simple URL shortener. The program will take a URL and provide a shortened version using slicing and concatenation.
Input: Enter a URL: www.example.com
Output: Shortened URL: www.exa...com