Session 3 - Part 1 Flashcards
```
~~~
How can you convert a string to uppercase in Python?
You can utilize the upper() method.
How can you convert a given string to lowercase in Python?
You can utilize the lower() method.
How can you convert a given string to title case in Python?
You can utilize the title() method.
How can you remove leading and trailing whitespace characters from a string in Python?
You can achieve this by using the strip() method.
What is the output of this code?
my_string = ‘ the cat Sat on The Mat. ‘
print(my_string.upper())
(spaces before) THE CAT SAT ON THE MAT.
What is the output of this code?
my_string = ‘ the cat Sat on The Mat. ‘
print(my_string.lower())
(spaces before) the cat sat on the mat.
What is the output of this code?
my_string = ‘ the cat Sat on The Mat. ‘
print(my_string.title())
(spaces before) The Cat Sat On The Mat
What is the output of this code?
my_string = ‘ the cat Sat on The Mat. ‘
print(my_string.strip())
the cat Sat on The Mat.
What is the output of this code?
my_string = ‘ the cat Sat on The Mat. ‘
print(my_string.strip().lower())
the cat sat on the mat.
Explain the following Python code:
my_string = ‘ the cat Sat on The Mat. ‘
print(my_string.upper()) - (3)
This code defines a string variable my_string containing the text “the cat Sat on The Mat.” with leading and trailing whitespace characters.
The upper() string method is then applied to my_string, converting all characters in the string to uppercase.
Finally, the result, which is the string in uppercase, is printed to the output console.
Explain the following Python code - (2)
my_string = ‘ the cat Sat on The Mat. ‘
print(my_string.title())
This code takes the string stored in the variable my_string and prints it out in title case.
In title case, the first character of each word is capitalized, and the rest of the characters are in lowercase.
Explain the following Python code - (2)
my_string = ‘ the cat Sat on The Mat. ‘
print(my_string.strip())
This code removes leading and trailing whitespace characters (such as spaces, tabs, and newline characters) from the string stored in the variable my_string.
The strip() method is used to perform this operation, and the resulting string with whitespace removed is printed to the console.
You can combine these string methods (upper, lower, title, strip) like this:
my_string.strip().lower()
Explain the following Python code and how it combines string methods - (4)
my_string = ‘ the cat Sat on The Mat. ‘
print(my_string.strip().lower())
This code demonstrates the combination of string methods in Python.
First, the strip() method is applied to my_string to remove leading and trailing whitespace characters.
Then, the lower() method is applied to the resulting string, converting all characters to lowercase.
The combined effect of these methods is that the string is stripped of whitespace and converted to lowercase before being printed to the console.
Explain the meaning of the following string assignment (i.e., (i.e., “string assignment” refers to the process of assigning a string value to a variable) - (3)
my_string=”\n hello world \t”
In the given string assignment, my_string, the escape sequences \n and \t are used.
\n represents a newline character, causing the text “hello world” to start on a new line.
\t represents a tab character, adding tab spaces (equivalent to multiple spaces) before the text “hello world”.
Exercise
Change the following code so that it prints the string ‘All In Title Case’ and without the leading and trailing spaces.
Bonus points. Use an f-string to center the modified string in some asterisks like this ** Hello World! **
Code:
my_string=”\n hello world \t”
print(my_string)
my_string=”\n hello world \t”
print(f”{my_string.title().strip()}”)
Output:
* Hello World*
What are string member functions in Python - (3)
String member functions” refer to methods that are specific to strings and are accessed using dot notation.
These methods include functions to change the case of strings (e.g., lower(), upper(), title(), strip(), join strings (join()), split strings (split()), and others.
They are essential for string manipulation tasks in Python
Describe the importance of string member functions in Python - (2)
String member functions are essential for cleaning up and altering the case of strings.
This is not only useful for printing and other output purposes but also in cases where we need to compare strings ‘case-insensitively’ (in other words without caring whether something is upper- or lower-case).
Let’s imagine we have a password system for school district
Each time someone wants to get in they have to type the password (‘pencil’). But, to make things easier, we don’t want it to fail if they have the CAPS LOCK key on, or if they are German And Need To Capitalize Lots Of Words. Or if they have accidentally added a space or tab at the start of the string (YNiC screensaver unlock box - I’m looking at you!).
How might we do this? - Two ways - (2)
Using if statements
Turning any user input to lower case and check against ‘pencil’
Let’s imagine we have a password system for school district
Each time someone wants to get in they have to type the password (‘pencil’). But, to make things easier, we don’t want it to fail if they have the CAPS LOCK key on, or if they are German And Need To Capitalize Lots Of Words. Or if they have accidentally added a space or tab at the start of the string (YNiC screensaver unlock box - I’m looking at you!).
First way if statements:
if (inputWord==’pencil’) or (inputWord==’PENCIL’) or (inputWord==’Pencil’) or (inputWord=…..
Why might using a series of if statements to check for variations in capitalization or leading whitespace be considered clunky? - (2)
e.g.,
if (inputWord==’pencil’) or (inputWord==’PENCIL’) or (inputWord==’Pencil’) or (inputWord=…..
Using a series of if statements to check for variations in capitalization or leading whitespace can be considered clunky because it requires writing repetitive code and becomes cumbersome to maintain, especially if the password changes.
Also you may not think of all the variations people can type pencil
Let’s imagine we have a password system for school district
Each time someone wants to get in they have to type the password (‘pencil’). But, to make things easier, we don’t want it to fail if they have the CAPS LOCK key on, or if they are German And Need To Capitalize Lots Of Words. Or if they have accidentally added a space or tab at the start of the string (YNiC screensaver unlock box - I’m looking at you!).
Second way -Turning any user input to lower case and check against ‘pencil’ - produce this code - target string is ‘pencil’
target_string = ‘pencil’
user_input = input(‘Login with user password: ‘)
user_input = user_input.lower()
if user_input == target_string:
print(“Welcome to the Seattle Public School District DATANET”)
else:
print(“Password denied”)
What is the following outputs given these inputs? - (5)
code:
target_string = ‘pencil’
user_input = input(‘Login with user password: ‘)
user_input = user_input.lower() # We could also ‘strip’ it to remove whitespace
if user_input == target_string:
print(“Welcome to the Seattle Public School District DATANET”)
else:
print(“Password denied”)
inputs: pencil PENCIL PeNCIL pen
Login with user password: pencil Welcome to the Seattle Public School District DATANET
Login with user password: Pencil Welcome to the Seattle Public School District DATANET
Login with user password: pencil Welcome to the Seattle Public School District DATANET
Login with user password: PeNCIL Welcome to the Seattle Public School District DATANET
Login with user password: pen Password denied
What is the advantage of converting the input to lowercase before comparing it to the password?
e.g.,
target_string = ‘pencil’
user_input = input(‘Login with user password: ‘)
user_input = user_input.lower()
Converting the input to lowercase before comparison ensures case insensitivity, simplifying code and making it more robust by ignoring variations in capitalization or leading whitespace.
Explain the following Python code - (6)
target_string = ‘pencil’
user_input = input(‘Login with user password: ‘)
user_input = user_input.lower()
if user_input == target_string:
print(“Welcome to the Seattle Public School District DATANET”)
else:
print(“Password denied”)
This code prompts the user to enter a password and compares it with a target password stored in lower case.
Firstly, the target password ‘pencil’ is stored as all lower-case characters in variable ‘target_string’
Then, the user is prompted to input their password.
The user_input.lower() function converts the user’s input to lower case, ensuring that the comparison is not case-sensitive.
If the user’s input matches the target password, ‘Welcome to the Seattle Public School District DATANET’ is printed; otherwise, ‘Password denied’ is printed.
This approach ensures that the password comparison ignores variations in capitalization and provides a robust password validation mechanism.
What is the output of this code?
target_string = ‘pencil’
user_input input(‘Login with user password’
might you use a while loop to keep going until someone gets the password right? BONUS POINTS: Why might this be a bad idea?
We will just keep trying lots of passwords
Quick Exercise
Modify the code from the example above so that it does the comparison in upper case.
target_string = ‘pencil’
user_input = input(‘Login with user password: ‘)
user_input = user_input.lower() # We could also ‘strip’ it to remove whitespace
if user_input == target_string:
print(“Welcome to the Seattle Public School District DATANET”)
else:
print(“Password denied”)
tgt_string = ‘PENCIL’
user_input = input(‘Enter a string: ‘)
user_input = user_input.upper()
if user_input == tgt_string:
print(“Welcome to the Seattle Public School District DATANET”)
else:
print(“Password denied”)
Explain the functionality of the split string member function .spilt() in Python.
The split string member function is designed to take a string and split it into a list of strings
What is the default behaviour of .spilt() string member function?
By default, it splits the string on any whitespace characters (such as spaces, tabs, or newlines/carriage-return characters),
Explain the functionality of the provided Python code - (10)
dat = ‘The cat sat on the mat’
res = dat.split()
print(type(res))
print(res)
print(len(res))
The provided code utilizes the split() method to split the string “The cat sat on the mat” into individual words.
It initializes a string variable dat with the value ‘The cat sat on the mat’.
The split() method is applied to dat, splitting the string into individual words based on whitespace characters.
The resulting list is stored in the variable res.
It prints the type of res (which confirms it’s a list), the contents of res (the individual words), and the length of res (the number of words in the original string).
Output:
<class ‘list’>
[‘The’, ‘cat’, ‘sat’, ‘on’, ‘the’, ‘mat’]
6
You can see that it takes the string “The cat sat on the mat” and breaks it apart into 6 strings - one for each part of the string between each space character.
The length of the resulting list is 6, corresponding to the number of words in the original string.
Explain how to change the character on which the split method splits a string in Python,
To change the character on which the split method splits a string, you can pass a desired ‘separator’ character as an argument to the method.
Example of change the character on which spilt spilts the string by passing our desired ‘seprator; character as an arguement - (2)
if we have a string which is separated by commas:
dat = ‘Person,Condition,RT’
res = dat.split(‘,’)
print(res)
Explain:
In this example, the string dat is split into individual parts at each comma character, and the resulting list is printed:
Output:
[‘Person’, ‘Condition’, ‘RT’]
Why is this formulation particularly useful e.g., spilting string based on comma character ‘,’:
dat = ‘Person,Condition,RT’
res = dat.split(‘,’)
print(res)
This formulation is particularly useful because a common way to store data in scientific studies is as a Comma-Separated Values file (often known as a CSV file).
Modify this code below to spilt on a different character like ‘o’:
dat = ‘Person,Condition,RT’
res = dat.split(‘,’)
print(res)
dat = ‘Person,Condition,RT’
res = dat.split(‘o’)
print(res)
What is output of this code:
dat = ‘Person,Condition,RT’
res = dat.split(‘o’)
print(res)
[‘Pers’, ‘n,C’, ‘nditi’, ‘n,RT’]
Explain this code - (5)
dat = ‘Person,Condition,RT’
res = dat.split(‘o’)
print(res)
The string ‘Person,Condition,RT’ is stored in the variable dat.
The split(‘o’) method is applied to dat, splitting the string at each occurrence of the letter ‘o’.
The resulting list is stored in the variable res.
It prints the content of res, which contains the parts of the string split at each occurrence of ‘o’.
So output would be: [‘Pers’, ‘n,C’, ‘nditi’, ‘n,RT’]
Explain the concept of “white-space” in Python and what it refers to - (2)
In Python, “white-space” refers to characters such as tabs, spaces, and newline/carriage-return characters.
These characters are used to format code or data files and are typically invisible when displayed.
What does “carriage return” mean in the context of datafiles? - (2)
n data files, “carriage return” indicates the end of a line in a datafile.
In Python, it is represented by the special symbol \n, which is interpreted as a “newline” character.