Strings, String and List Methods, Exceptions Flashcards

1
Q

What is the most widely used code to turn characters into numbers?

A

ASCII short for American Standard Code for Information Interchange

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What does I18N stand for?

A

Internationalisation

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is a code point?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is a code page?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What does unicode do?

A

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).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What does UCS-4 do?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Are strings mutable or immutable?

A

immutable

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

i_am = ‘I\‘m’
print(len(i_am))

What is the output?

A

3
i ‘ m

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

multiline = ‘Line #1
Line #2’

print(len(multiline))

What is the ouput?

A

Syntax Error

string cannot be on more than 1 line in ‘’ need to use ‘’’ ‘’’ or “”” “””

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

multiline = “"”Line #1
Line #2”””

print(len(multiline))

what is the output?

A

15

as there is a white space \n between the two lines that need to be counted

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What are the two operations you can perform on strings?

A

concatenation +
replication *

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is overloading?

A

The ability to use the same operator against completely different kinds of data

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What does ord do and what is its requirement?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What does char() do?

A

code point number –> corresponding character

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

ORD() NEEDS A STRING !!!!!!!!!!!
CHR() NEEDS A INT !!!!!!!!!!!!!!!

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Strings are sequences therefore you can ….

A

iterate through them and index them

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What is slicing?

A

taking a part of a string

e.g. x = kate
x[2:4]
–> te

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

alphabet = “abcdefghijklmnopqrstuvwxyz”

print(“f” in alphabet)

what is the output?

A

True

can also use not in

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What three things can you not do with a string that you can with a list?

A

del (a specific element)
insert
append

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

alphabet = “bcdefghijklmnopqrstuvwxy”

alphabet = “a” + alphabet

What is the output?

A

“abcdefghijklmnopqrstuvwxy”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

t = ‘The Knights Who Say “Ni!”’
min(t)

A

the space ‘ ‘

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

What will cause an error using the min()?

A

if the string or list is empty

Value Error

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

print(min(“aAbByYzZ”))

A

A

comes first in ASCII

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

print(max(“aAbByYzZ”))

A

z

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

print(“aAbByYzZaA”.index(“b”))

A

2

Note: the element searched for must occur in the sequence - its absence will cause a ValueError exception.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

What does the index method do?

A

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).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

What does the list function do?

A

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’]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

What does the count method do?

A

The count() method counts all occurrences of the element inside the sequence. The absence of such elements doesn’t cause any problems.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

for ch in “abc”:
print(chr(ord(ch) + 1), end=’’)

What is the output?

A

bcd

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

What does the capitalize() method do?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

print(‘ Alpha’.capitalize())

A

’ alpha’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

What does center() do?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

print(‘[’ + ‘gamma’.center(20, ‘*’) + ‘]’)

A

[**gamma***]

(brainscape messed up should be 20 characters over all)

34
Q

What does the endswith() method do?

A

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

35
Q

What does the find() method do?

A

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

36
Q

What does two parameter find() do?

A

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

37
Q

What does isalnum() do ?

A

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

38
Q

What does isalpha() do?

A

checks if the string only contains letters

39
Q

What does isdigit() do?

A

checks if string only contains digits

40
Q

What does islower() so?

A

returns true is all characters are lower case

41
Q

What does isspace() do?

A

The isspace() method identifies whitespaces only - it disregards any other character (the result is False then).

42
Q

What does isupper() do?

A

returns true is all characters are upper case

43
Q

What does the join() method do?

A

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

44
Q

What does lower() do?

A

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.

45
Q

What does the lstrip() method do?

A

The parameterless lstrip() method returns a newly created string formed from the original one by removing all leading whitespaces.

46
Q

print(“www.cisco.com”.lstrip(“w.”))

A

cisco.com

print(“www.wwwww…w….cisco.com”.lstrip(“w.”))

—> cisco.com

47
Q

What does the replace() method do?

A

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.

48
Q

What does the third parameter in replace() do?

A

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!

49
Q

What does rfind() method do?

A

Same as find() but starts search from the end of the string

can have three parameters
what to search for , start, finish

50
Q

What does rstrip() do?

A

same as lstrip() but starts from end of string

print(“cisco.com”.rstrip(“.com”))
——-> cis

51
Q

What does split() do?

A

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.

52
Q

What does startswith() do?

A

The startswith() method is a mirror reflection of endswith() - it checks if a given string starts with the specified substring.

53
Q

What does strip() do?

A

The strip() method combines the effects caused by rstrip() and lstrip() - it makes a new string lacking all the leading and trailing whitespaces.

54
Q

What does swapcase() do?

A

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.

55
Q

What does title() do?

A

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.

56
Q

What does upper() do?

A

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.

57
Q

How does python compare strings?

A

It compares them using the normal comparisons e.g. ==, !=, >, >=, <, <=

using the character ASCII code

therefore

‘A’ < ‘a’

58
Q

Output of ‘80’ > ‘20’

A

True but remember they are strings so the comparison is the ASCII code point

59
Q

What are the only two comparison you can perform against ints and strings?

e.g. 10 ……. ‘10’

A

== and !=

> and < will give a type error

60
Q

Whats the difference between sort() and sorted()?

A

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.

61
Q

How do you convert a number (int or float) to a string?

A

str(number)

62
Q

How do you convert a string to a number (int or float)?

A

Only works if the string is a valid number. will get a value error if not.

int(num)
float(num)

63
Q

True or False ‘11’ < ‘8’?

A

True as ‘11’ is just two 1s which come before 8 and therefore have lower ASCII number

64
Q

s1 = ‘Where are the snows of yesteryear?’
s2 = s1.split()
s3 = sorted(s2)
print(s3[1])

A

are

because Where has a capital and therefore comes first in ASCII values

65
Q

try:
print(“1”)
x = 1 / 0
print(“2”)
except:
print(“Oh dear, something went wrong…”)

print(“3”)

A

1
Oh dear, something went wrong…
3

66
Q

What order are except branches searched in?

A

The same order they appear in the code

67
Q

try:
print(“Let’s try to do this”)
print(“#”[2])
print(“We succeeded!”)
except:
print(“We failed”)
print(“We’re done”)

A

Let’s try to do this
We failed
We’re done

(index error in line 3)

68
Q

How would you handle two or more exceptions in the same way?

A

try:
:
except (exc1, exc2):
:

69
Q

What does raise exc do?

A

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).

70
Q

Where can ‘raise’ be used on its own?

A

Inside the expect branch

71
Q

What does assert expression do?

A

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.

72
Q

Describe Arithmetic Error?

A

Location: BaseException ← Exception ← ArithmeticError

Description: an abstract exception including all exceptions caused by arithmetic operations like zero division or an argument’s invalid domain

73
Q

Describe Assertion Error

A

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

74
Q

Describe Base Exception

A

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:.

75
Q

Describe Index Error

A

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)

76
Q

Describe Keyboard Interrupt

A

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.

77
Q

Describe Lookup Error

A

BaseException ← Exception ← LookupError

Description: an abstract exception including all exceptions caused by errors resulting from invalid references to different collections (lists, dictionaries, tuples, etc.)

78
Q

Describe Memory Error

A

Location: BaseException ← Exception ← MemoryError

Description: a concrete exception raised when an operation cannot be completed due to a lack of free memory.

79
Q

Describe Overflow Error

A

Location: BaseException ← Exception ← ArithmeticError ← OverflowError

Description: a concrete exception raised when an operation produces a number too big to be successfully stored

80
Q

Describe Import Error

A

Location: BaseException ← Exception ← StandardError ← ImportError

Description: a concrete exception raised when an import operation fails

81
Q

Describe Key Error

A

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)

82
Q

print(ord(‘c’) - ord(‘a’))

A

2