Strings, String and List Methods, Exceptions Flashcards
What is the most widely used code to turn characters into numbers?
ASCII short for American Standard Code for Information Interchange
What does I18N stand for?
Internationalisation
What is a code point?
A code point is a number which makes a character. For example, 32 is a code point which makes a space in ASCII encoding. We can say that standard ASCII code consists of 128 code points.
What is a code page?
A code page is a standard for using the upper 128 code points to store specific national characters. For example, there are different code pages for Western Europe and Eastern Europe, Cyrillic and Greek alphabets, Arabic and Hebrew languages, and so on.
What does unicode do?
Unicode assigns unique (unambiguous) characters (letters, hyphens, ideograms, etc.) to more than a million code points.
The first 128 Unicode code points are identical to ASCII, and the first 256 Unicode code points are identical to the ISO/IEC 8859-1 code page (a code page designed for western European languages).
What does UCS-4 do?
UCS-4.
The name comes from Universal Character Set.
UCS-4 uses 32 bits (four bytes) to store each character, and the code is just the Unicode code points’ unique number. A file containing UCS-4 encoded text may start with a BOM (byte order mark), an unprintable combination of bits announcing the nature of the file’s contents. Some utilities may require it.
Are strings mutable or immutable?
immutable
i_am = ‘I\‘m’
print(len(i_am))
What is the output?
3
i ‘ m
multiline = ‘Line #1
Line #2’
print(len(multiline))
What is the ouput?
Syntax Error
string cannot be on more than 1 line in ‘’ need to use ‘’’ ‘’’ or “”” “””
multiline = “"”Line #1
Line #2”””
print(len(multiline))
what is the output?
15
as there is a white space \n between the two lines that need to be counted
What are the two operations you can perform on strings?
concatenation +
replication *
What is overloading?
The ability to use the same operator against completely different kinds of data
What does ord do and what is its requirement?
ord() (ordinal) turns character in ASCII code point value
The function needs a one-character string as its argument - breaching this requirement causes a TypeError exception, and returns a number representing the argument’s code point.
What does char() do?
code point number –> corresponding character
ORD() NEEDS A STRING !!!!!!!!!!!
CHR() NEEDS A INT !!!!!!!!!!!!!!!
Strings are sequences therefore you can ….
iterate through them and index them
What is slicing?
taking a part of a string
e.g. x = kate
x[2:4]
–> te
alphabet = “abcdefghijklmnopqrstuvwxyz”
print(“f” in alphabet)
what is the output?
True
can also use not in
What three things can you not do with a string that you can with a list?
del (a specific element)
insert
append
alphabet = “bcdefghijklmnopqrstuvwxy”
alphabet = “a” + alphabet
What is the output?
“abcdefghijklmnopqrstuvwxy”
t = ‘The Knights Who Say “Ni!”’
min(t)
the space ‘ ‘
What will cause an error using the min()?
if the string or list is empty
Value Error
print(min(“aAbByYzZ”))
A
comes first in ASCII
print(max(“aAbByYzZ”))
z
print(“aAbByYzZaA”.index(“b”))
2
Note: the element searched for must occur in the sequence - its absence will cause a ValueError exception.
What does the index method do?
The index() method (it’s a method, not a function) searches the sequence from the beginning, in order to find the first element of the value specified in its argument.
The method returns the index of the first occurrence of the argument (which means that the lowest possible result is 0, while the highest is the length of argument decremented by 1).
What does the list function do?
The list() function takes its argument (a string) and creates a new list containing all the string’s characters, one per list element.
print(list(“abcabc”))
–>[‘a’, ‘b’, ‘c’, ‘a’, ‘b’, ‘c’]
What does the count method do?
The count() method counts all occurrences of the element inside the sequence. The absence of such elements doesn’t cause any problems.
for ch in “abc”:
print(chr(ord(ch) + 1), end=’’)
What is the output?
bcd
What does the capitalize() method do?
if the first character inside the string is a letter (note: the first character is an element with an index equal to 0, not just the first visible character), it will be converted to upper-case;
all remaining letters from the string will be converted to lower-case.
print(‘ Alpha’.capitalize())
’ alpha’
What does center() do?
The one-parameter variant of the center() method makes a copy of the original string, trying to center it inside a field of a specified width.
The centering is actually done by adding some spaces before and after the string
The two-parameter variant of center() makes use of the character from the second argument, instead of a space.
print(‘[’ + ‘gamma’.center(20, ‘*’) + ‘]’)
[**gamma***]
(brainscape messed up should be 20 characters over all)
What does the endswith() method do?
checks if the given string ends with the specified argument and returns True or False, depending on the check result.
if “epsilon”.endswith(“on”):
print(“yes”)
else:
print(“no”)
yes
What does the find() method do?
The find() method is similar to index(), which you already know - it looks for a substring and returns the index of first occurrence of this substring, but:
it’s safer - it doesn’t generate an error for an argument containing a non-existent substring (it returns -1 then)
it works with strings only - don’t try to apply it to any other sequence.
print(“Eta”.find(“ta”)) –> 1
print(“Eta”.find(“mma”)) –> -1
What does two parameter find() do?
if you want to perform the find, not from the string’s beginning, but from any position, you can use a two-parameter variant of the find() method. Look at the example:
print(‘kappa’.find(‘a’, 2)) —> 4
There is also a three-parameter mutation of the find() method - the third argument points to the first index which won’t be taken into consideration during the search (it’s actually the upper limit of the search).
print(‘kappa’.find(‘a’, 2, 4)) ——–> -1
What does isalnum() do ?
The parameterless method named isalnum() checks if the string contains only digits or alphabetical characters (letters), and returns True or False according to the result.
spaces are not a digit or a char
What does isalpha() do?
checks if the string only contains letters
What does isdigit() do?
checks if string only contains digits
What does islower() so?
returns true is all characters are lower case
What does isspace() do?
The isspace() method identifies whitespaces only - it disregards any other character (the result is False then).
What does isupper() do?
returns true is all characters are upper case
What does the join() method do?
the method performs a join - it expects one argument as a list; it must be assured that all the list’s elements are strings - the method will raise a TypeError exception otherwise;
all the list’s elements will be joined into one string but…
…the string from which the method has been invoked is used as a separator, put among the strings;
print(“,”.join([“omicron”, “pi”, “rho”]))
–> omicron,pi,rho
What does lower() do?
The lower() method makes a copy of a source string, replaces all upper-case letters with their lower-case counterparts, and returns the string as the result. Again, the source string remains untouched.
What does the lstrip() method do?
The parameterless lstrip() method returns a newly created string formed from the original one by removing all leading whitespaces.
print(“www.cisco.com”.lstrip(“w.”))
cisco.com
print(“www.wwwww…w….cisco.com”.lstrip(“w.”))
—> cisco.com
What does the replace() method do?
The two-parameter replace() method returns a copy of the original string in which all occurrences of the first argument have been replaced by the second argument.
What does the third parameter in replace() do?
Limits the number of replacements
print(“This is it!”.replace(“is”, “are”, 1))—–thare is it!
print(“This is it!”.replace(“is”, “are”, 2))—thare are it!
What does rfind() method do?
Same as find() but starts search from the end of the string
can have three parameters
what to search for , start, finish
What does rstrip() do?
same as lstrip() but starts from end of string
print(“cisco.com”.rstrip(“.com”))
——-> cis
What does split() do?
The split() method does what it says - it splits the string and builds a list of all detected substrings.
The method assumes that the substrings are delimited by whitespaces - the spaces don’t take part in the operation, and aren’t copied into the resulting list.
What does startswith() do?
The startswith() method is a mirror reflection of endswith() - it checks if a given string starts with the specified substring.
What does strip() do?
The strip() method combines the effects caused by rstrip() and lstrip() - it makes a new string lacking all the leading and trailing whitespaces.
What does swapcase() do?
The swapcase() method makes a new string by swapping the case of all letters within the source string: lower-case characters become upper-case, and vice versa.
What does title() do?
The title() method performs a somewhat similar function - it changes every word’s first letter to upper-case, turning all other ones to lower-case.
What does upper() do?
Last but not least, the upper() method makes a copy of the source string, replaces all lower-case letters with their upper-case counterparts, and returns the string as the result.
How does python compare strings?
It compares them using the normal comparisons e.g. ==, !=, >, >=, <, <=
using the character ASCII code
therefore
‘A’ < ‘a’
Output of ‘80’ > ‘20’
True but remember they are strings so the comparison is the ASCII code point
What are the only two comparison you can perform against ints and strings?
e.g. 10 ……. ‘10’
== and !=
> and < will give a type error
Whats the difference between sort() and sorted()?
sort() is a method which affects the list itself, no new list is created. Ordering is performed in situ by the method.
sorted() is a function. The function takes one argument and returns a new list.
How do you convert a number (int or float) to a string?
str(number)
How do you convert a string to a number (int or float)?
Only works if the string is a valid number. will get a value error if not.
int(num)
float(num)
True or False ‘11’ < ‘8’?
True as ‘11’ is just two 1s which come before 8 and therefore have lower ASCII number
s1 = ‘Where are the snows of yesteryear?’
s2 = s1.split()
s3 = sorted(s2)
print(s3[1])
are
because Where has a capital and therefore comes first in ASCII values
try:
print(“1”)
x = 1 / 0
print(“2”)
except:
print(“Oh dear, something went wrong…”)
print(“3”)
1
Oh dear, something went wrong…
3
What order are except branches searched in?
The same order they appear in the code
try:
print(“Let’s try to do this”)
print(“#”[2])
print(“We succeeded!”)
except:
print(“We failed”)
print(“We’re done”)
Let’s try to do this
We failed
We’re done
(index error in line 3)
How would you handle two or more exceptions in the same way?
try:
:
except (exc1, exc2):
:
What does raise exc do?
The raise instruction raises the specified exception named exc as if it was raised in a normal (natural) way:
raise exc
The instruction enables you to:
simulate raising actual exceptions (e.g., to test your handling strategy)
partially handle an exception and make another part of the code responsible for completing the handling (separation of concerns).
Where can ‘raise’ be used on its own?
Inside the expect branch
What does assert expression do?
evaluates the expression and raises the AssertError exception when the expression is equal to zero, an empty string, or None. You can use it to protect some critical parts of your code from devastating data.
Describe Arithmetic Error?
Location: BaseException ← Exception ← ArithmeticError
Description: an abstract exception including all exceptions caused by arithmetic operations like zero division or an argument’s invalid domain
Describe Assertion Error
Location: BaseException ← Exception ← AssertionError
Description: a concrete exception raised by the assert instruction when its argument evaluates to False, None, 0, or an empty string
Describe Base Exception
Location: BaseException
Description: the most general (abstract) of all Python exceptions - all other exceptions are included in this one; it can be said that the following two except branches are equivalent: except: and except BaseException:.
Describe Index Error
Location: BaseException ← Exception ← LookupError ← IndexError
Description: a concrete exception raised when you try to access a non-existent sequence’s element (e.g., a list’s element)
Describe Keyboard Interrupt
Location: BaseException ← KeyboardInterrupt
Description: a concrete exception raised when the user uses a keyboard shortcut designed to terminate a program’s execution (Ctrl-C in most OSs); if handling this exception doesn’t lead to program termination, the program continues its execution.
Note: this exception is not derived from the Exception class. Run the program in IDLE.
Describe Lookup Error
BaseException ← Exception ← LookupError
Description: an abstract exception including all exceptions caused by errors resulting from invalid references to different collections (lists, dictionaries, tuples, etc.)
Describe Memory Error
Location: BaseException ← Exception ← MemoryError
Description: a concrete exception raised when an operation cannot be completed due to a lack of free memory.
Describe Overflow Error
Location: BaseException ← Exception ← ArithmeticError ← OverflowError
Description: a concrete exception raised when an operation produces a number too big to be successfully stored
Describe Import Error
Location: BaseException ← Exception ← StandardError ← ImportError
Description: a concrete exception raised when an import operation fails
Describe Key Error
Location: BaseException ← Exception ← LookupError ← KeyError
Description: a concrete exception raised when you try to access a collection’s non-existent element (e.g., a dictionary’s element)
print(ord(‘c’) - ord(‘a’))
2