Deck 8: Strings: a Deeper Look
Question
Question
Question
Question
Question
Question
Question
Question
Question
Question
Question
Question
Question
Question
Question
Question
Question
Question
Question
Question
Unlock Deck
Sign up to unlock the cards in this deck!
Unlock Deck
Unlock Deck
1/20
Play
Full screen (f)
Deck 8: Strings: a Deeper Look
1
Based on the string sentence = '\t \n This is a test string. \t\t \n'
Which of the following statements is false?
A) There are several string methods for xe "stripping whitespace"xe "whitespace:removing"xe "removing whitespace"removing whitespace from the ends of a string. Because strings are immutable each returns a new string leaving the original unmodified.
B) The following code uses string method strip to remove the leading and trailing whitespace from sentence: sentence.strip()
C) The following code snippets first use method xe "string built-in type:lstrip"xe "lstrip string method"lstrip to remove only leading whitespace from sentence: sentence.lstrip()
Then use method xe "string built-in type:rstrip"xe "rstrip string method"rstrip to remove only trailing whitespace:
Sentence.rstrip()
D) Methods strip, lstrip and rstrip remove only leading and/or trailing spaces.
Which of the following statements is false?
A) There are several string methods for xe "stripping whitespace"xe "whitespace:removing"xe "removing whitespace"removing whitespace from the ends of a string. Because strings are immutable each returns a new string leaving the original unmodified.
B) The following code uses string method strip to remove the leading and trailing whitespace from sentence: sentence.strip()
C) The following code snippets first use method xe "string built-in type:lstrip"xe "lstrip string method"lstrip to remove only leading whitespace from sentence: sentence.lstrip()
Then use method xe "string built-in type:rstrip"xe "rstrip string method"rstrip to remove only trailing whitespace:
Sentence.rstrip()
D) Methods strip, lstrip and rstrip remove only leading and/or trailing spaces.
D
2
Which of the following statements is false?
A) f-strings were added to Python in Python 3.6.
B) You'll often see the format method in the Python documentation and in the many Python books and articles written before f-strings were introduced.
C) The following code formats the float value 17.489 rounded to the hundredths position: '{:.3f}'.format(17.489)
D) All of the above statements are true.
A) f-strings were added to Python in Python 3.6.
B) You'll often see the format method in the Python documentation and in the many Python books and articles written before f-strings were introduced.
C) The following code formats the float value 17.489 rounded to the hundredths position: '{:.3f}'.format(17.489)
D) All of the above statements are true.
C
3
Which of the following statements a), b) or c) is false?
A) For extremely large and small values of floating-point and Decimal types, xe "exponential notation"exponential (scientific) notation can be used to format the values more compactly.
B) The following interactive session shows the difference between f and e for a large value, each with three digits of precision to the right of the decimal point: In [1]: from decimal import Decimal
In [2]: f'{Decimal("10000000000000000000000000.0"):.3f}'
Out[2]: '10000000000000000000000000.000'
In [3]: f'{Decimal("10000000000000000000000000.0"):.3e}'
Out[3]: '1.000e+25'
C) For the e presentation type in snippet [3] of Part (c), the formatted value 1.000e+25 is equivalent to 1.000 x 1025. If you prefer a capital E for the exponent, use the E presentation type rather than
E)
D) All of the above statements are true.
A) For extremely large and small values of floating-point and Decimal types, xe "exponential notation"exponential (scientific) notation can be used to format the values more compactly.
B) The following interactive session shows the difference between f and e for a large value, each with three digits of precision to the right of the decimal point: In [1]: from decimal import Decimal
In [2]: f'{Decimal("10000000000000000000000000.0"):.3f}'
Out[2]: '10000000000000000000000000.000'
In [3]: f'{Decimal("10000000000000000000000000.0"):.3e}'
Out[3]: '1.000e+25'
C) For the e presentation type in snippet [3] of Part (c), the formatted value 1.000e+25 is equivalent to 1.000 x 1025. If you prefer a capital E for the exponent, use the E presentation type rather than
E)
D) All of the above statements are true.
D
4
Which of the following statements a), b) or c) is false?
A) String method count returns the number of times its argument occurs in the string on which the method is called.
B) If you specify as the second argument to method count a start_index, as in sentence.count('to', 12)
Count searches only the slice string[start_index:]-that is, from start_index through end of the string.
C) If you specify as the second and third arguments of method count the start_index and end_index, as in sentence.count('that', 12, 25)
Count searches only the slice string[start_index:end_index]-that is, from start_index up to, but not including, end_index.
D) All of the above statements are true.
A) String method count returns the number of times its argument occurs in the string on which the method is called.
B) If you specify as the second argument to method count a start_index, as in sentence.count('to', 12)
Count searches only the slice string[start_index:]-that is, from start_index through end of the string.
C) If you specify as the second and third arguments of method count the start_index and end_index, as in sentence.count('that', 12, 25)
Count searches only the slice string[start_index:end_index]-that is, from start_index up to, but not including, end_index.
D) All of the above statements are true.
Unlock Deck
Unlock for access to all 20 flashcards in this deck.
Unlock Deck
k this deck
5
Which of the following statements a), b) or c) is false?
A) Method replace takes two substrings. It searches a string for the substring in its first argument and replaces each occurrence with the substring in its second argument. The method returns a new string containing the results.
B) The following code replaces tab characters with commas: values = '1\t2\t3\t4\t5'
Values.replace('\t', ', ')
C) Method replace can receive an optional third argument specifying the maximum number of replacements to perform.
D) All of the above statements are true.
A) Method replace takes two substrings. It searches a string for the substring in its first argument and replaces each occurrence with the substring in its second argument. The method returns a new string containing the results.
B) The following code replaces tab characters with commas: values = '1\t2\t3\t4\t5'
Values.replace('\t', ', ')
C) Method replace can receive an optional third argument specifying the maximum number of replacements to perform.
D) All of the above statements are true.
Unlock Deck
Unlock for access to all 20 flashcards in this deck.
Unlock Deck
k this deck
6
Which of the following statements a), b) or c) is false?
A) String method splitlines returns a list of strings representing the lines of text split at each newline character in the original string.
B) Python stores multi-line strings with embedded \n characters to represent the line breaks.
C) For the string lines = """This is line 1
This is line2
This is line3"""
The statement
Lines.splitlines(True)
Keeps the newlines and returns:
['This is line 1', '\nThis is line2', '\nThis is line3']
D) All of the above statements are true.
A) String method splitlines returns a list of strings representing the lines of text split at each newline character in the original string.
B) Python stores multi-line strings with embedded \n characters to represent the line breaks.
C) For the string lines = """This is line 1
This is line2
This is line3"""
The statement
Lines.splitlines(True)
Keeps the newlines and returns:
['This is line 1', '\nThis is line2', '\nThis is line3']
D) All of the above statements are true.
Unlock Deck
Unlock for access to all 20 flashcards in this deck.
Unlock Deck
k this deck
7
Which of the following statements a), b) or c) is false?
A) You can xe "numbers:format with their signs (+"xe "string formatting:numbers with their signs (+)"force the sign on a positive number to display, as in: f'[{27:+10d}]'
B) The + before the field width in Part (a) specifies that a positive number should be preceded by a +. A negative number always starts with a -.
C) To xe "string formatting:fill with 0s"xe "fill with 0s"fill the remaining characters of a field with 0s rather than spaces, place a 0 before the field width (and after the + if there is one), as in: f'[{27:+010d}]'
D) All of the above statements are true.
A) You can xe "numbers:format with their signs (+"xe "string formatting:numbers with their signs (+)"force the sign on a positive number to display, as in: f'[{27:+10d}]'
B) The + before the field width in Part (a) specifies that a positive number should be preceded by a +. A negative number always starts with a -.
C) To xe "string formatting:fill with 0s"xe "fill with 0s"fill the remaining characters of a field with 0s rather than spaces, place a 0 before the field width (and after the + if there is one), as in: f'[{27:+010d}]'
D) All of the above statements are true.
Unlock Deck
Unlock for access to all 20 flashcards in this deck.
Unlock Deck
k this deck
8
Which of the following statements is false?
A) By default, the following f-strings xe "string formatting:right align (\>"xe "right align \>"right-align the numeric values 27 and 3.5 and xe "string formatting:left align (\)"xe "left align (\) in string formatting"left-align the string "hello": f'[{27:10d}]'
F'[{3.5:10f}]'
F'[{"hello":10}]'
B) Python formats float values with six digits of precision to the right of the decimal point by default.
C) For formatted values that have fewer characters than the field width, the remaining character positions are filled with spaces.
D) Formatted values with more characters than the field width cause a ValueError.
A) By default, the following f-strings xe "string formatting:right align (\>"xe "right align \>"right-align the numeric values 27 and 3.5 and xe "string formatting:left align (\)"xe "left align (\) in string formatting"left-align the string "hello": f'[{27:10d}]'
F'[{3.5:10f}]'
F'[{"hello":10}]'
B) Python formats float values with six digits of precision to the right of the decimal point by default.
C) For formatted values that have fewer characters than the field width, the remaining character positions are filled with spaces.
D) Formatted values with more characters than the field width cause a ValueError.
Unlock Deck
Unlock for access to all 20 flashcards in this deck.
Unlock Deck
k this deck
9
Which of the following statements is false?
A) The following f-string formats the float value 17.489 rounded to the hundredths position: f'{17.489:.2f}'
B) Python supports precision only for floating-point and Decimal values.
C) Formatting is xe "formatting:type dependent"xe "type dependent formatting"type dependent-if you try to use .2f to format a string like 'hello', a NameError occurs.
D) The presentation type f in the xe "format specifier"format specifier .2f is required.
A) The following f-string formats the float value 17.489 rounded to the hundredths position: f'{17.489:.2f}'
B) Python supports precision only for floating-point and Decimal values.
C) Formatting is xe "formatting:type dependent"xe "type dependent formatting"type dependent-if you try to use .2f to format a string like 'hello', a NameError occurs.
D) The presentation type f in the xe "format specifier"format specifier .2f is required.
Unlock Deck
Unlock for access to all 20 flashcards in this deck.
Unlock Deck
k this deck
10
Which of the following statements a), b) or c) is false?
A) A space before the presentation type in an f-string indicates that positive numbers should show a space character in the sign position. This is useful for aligning positive and negative values for display purposes, as in: In [1]: print(f'{27: d}\n{-27: d}')
27
-27
B) If a field width is specified with a space flag, the space should appear before the field width.
C) You can format numbers with thousands separators by using a comma (,), as in the following f-strings: f'{,12345678:d}'
F'{,123456.78:.2f}'
D) All of the above statements are true.
A) A space before the presentation type in an f-string indicates that positive numbers should show a space character in the sign position. This is useful for aligning positive and negative values for display purposes, as in: In [1]: print(f'{27: d}\n{-27: d}')
27
-27
B) If a field width is specified with a space flag, the space should appear before the field width.
C) You can format numbers with thousands separators by using a comma (,), as in the following f-strings: f'{,12345678:d}'
F'{,123456.78:.2f}'
D) All of the above statements are true.
Unlock Deck
Unlock for access to all 20 flashcards in this deck.
Unlock Deck
k this deck
11
Which of the following statements a), b) or c) is false?
A) Strings can be compared with the comparison operators. Recall that strings are compared based on their underlying integer numeric values. So uppercase letters compare as less than lowercase letters because uppercase letters have lower integer values.
B) You can check character codes with ord. For example, the following code displays the values 65 and 97 for A and a, respectively: print(f'A: {ord("A")}; a: {ord("a")}')
C) In the following interactive session that compares the strings 'Orange' and 'orange', the outputs of snippets [2] and [6] (marked as ???) are False and True: In [1]: 'Orange' == 'orange'
Out[1]: False
In [2]: 'Orange' != 'orange'
Out[2]: ???
In [3]: 'Orange' < 'orange'
Out[3]: True
In [4]: 'Orange' <= 'orange'
Out[4]: True
In [5]: 'Orange' > 'orange'
Out[5]: False
In [6]: 'Orange' >= 'orange'
Out[6]: ???
D) All of the above statements are true.
A) Strings can be compared with the comparison operators. Recall that strings are compared based on their underlying integer numeric values. So uppercase letters compare as less than lowercase letters because uppercase letters have lower integer values.
B) You can check character codes with ord. For example, the following code displays the values 65 and 97 for A and a, respectively: print(f'A: {ord("A")}; a: {ord("a")}')
C) In the following interactive session that compares the strings 'Orange' and 'orange', the outputs of snippets [2] and [6] (marked as ???) are False and True: In [1]: 'Orange' == 'orange'
Out[1]: False
In [2]: 'Orange' != 'orange'
Out[2]: ???
In [3]: 'Orange' < 'orange'
Out[3]: True
In [4]: 'Orange' <= 'orange'
Out[4]: True
In [5]: 'Orange' > 'orange'
Out[5]: False
In [6]: 'Orange' >= 'orange'
Out[6]: ???
D) All of the above statements are true.
Unlock Deck
Unlock for access to all 20 flashcards in this deck.
Unlock Deck
k this deck
12
Consider the following code: In [1]: s1 = 'happy'
In [2]: s2 = 'birthday'
In [3]: s1 += ' ' + s2
In [4]: s1
Out[4]: 'happy birthday'
In [5]: symbol = '>'
In [6]: symbol *= 5
In [7]: symbol
Out[7]: '>>>>>'
Which snippet(s) in this interactive session appear to modify existing strings, but actually create new string objects?
A) Only snippet [3].
B) Only snippet [5].
C) Both snippets [5] and [6].
D) Both snippets [3] and [6].
In [2]: s2 = 'birthday'
In [3]: s1 += ' ' + s2
In [4]: s1
Out[4]: 'happy birthday'
In [5]: symbol = '>'
In [6]: symbol *= 5
In [7]: symbol
Out[7]: '>>>>>'
Which snippet(s) in this interactive session appear to modify existing strings, but actually create new string objects?
A) Only snippet [3].
B) Only snippet [5].
C) Both snippets [5] and [6].
D) Both snippets [3] and [6].
Unlock Deck
Unlock for access to all 20 flashcards in this deck.
Unlock Deck
k this deck
13
Which of the following statements a), b) or c) is false?
A) String methods xe "string built-in type:lower method"xe "lower method of a string"lower and xe "string built-in type:upper method"xe "upper method of a string"upper can convert strings to all lowercase or all uppercase letters, respectively.
B) Method capitalize copies the original string and returns a new string with only the first letter capitalized (sometimes called xe "capitalization:sentence"xe "sentence capitalization"sentence capitalization).
C) Method title copies the original string and returns a new string with only the first character of each word capitalized (sometimes called xe "capitalization:book title"xe "book-title capitalization"book-title capitalization).
D) All of the above statements are true.
A) String methods xe "string built-in type:lower method"xe "lower method of a string"lower and xe "string built-in type:upper method"xe "upper method of a string"upper can convert strings to all lowercase or all uppercase letters, respectively.
B) Method capitalize copies the original string and returns a new string with only the first letter capitalized (sometimes called xe "capitalization:sentence"xe "sentence capitalization"sentence capitalization).
C) Method title copies the original string and returns a new string with only the first character of each word capitalized (sometimes called xe "capitalization:book title"xe "book-title capitalization"book-title capitalization).
D) All of the above statements are true.
Unlock Deck
Unlock for access to all 20 flashcards in this deck.
Unlock Deck
k this deck
14
Which of the following statements is false?
A) The d presentation type in the following f-string formats strings as integer values: f'{10:d}'
B) The xe "presentation type (string formatting):integers in binary, octal or hexadecimal number systems"xe "integer:presentations types"integer presentation types b, o and x or X format integers using the xe "number systems:binary"xe "binary number system"binary, xe "number systems:octal"xe "octal number system"octal or xe "number systems:hexadecimal"xe "hexadecimal number system"hexadecimal number systems, respectively.
C) The xe "c presentation type"c presentation type in the following f-string formats an integer character code as the corresponding character: f'{65:c} {97:c}'
D) If you do not specify a presentation type, as in the second placeholder below, non-string values like the integer 7 are converted to strings: f'{"hello":s} {7}'
A) The d presentation type in the following f-string formats strings as integer values: f'{10:d}'
B) The xe "presentation type (string formatting):integers in binary, octal or hexadecimal number systems"xe "integer:presentations types"integer presentation types b, o and x or X format integers using the xe "number systems:binary"xe "binary number system"binary, xe "number systems:octal"xe "octal number system"octal or xe "number systems:hexadecimal"xe "hexadecimal number system"hexadecimal number systems, respectively.
C) The xe "c presentation type"c presentation type in the following f-string formats an integer character code as the corresponding character: f'{65:c} {97:c}'
D) If you do not specify a presentation type, as in the second placeholder below, non-string values like the integer 7 are converted to strings: f'{"hello":s} {7}'
Unlock Deck
Unlock for access to all 20 flashcards in this deck.
Unlock Deck
k this deck
15
Which of the following statements a), b) or c) is false?
A) A format string may contain multiple placeholders, in which case the format method's arguments correspond to the placeholders from left to right: '{} {}'.format('Amanda', 'Cyan')
B) The format string can reference specific arguments by their position in the format method's argument list, starting with position 0, as in: '{0} {0} {1}'.format('Happy', 'Birthday')
You can reference each argument as often as you like and in any order.
C) You can reference keyword arguments by their keys in the placeholders, as in: '{first} {last}'.format(first='Amanda', last='Gray')
'{last} {first}'.format(first='Amanda', last='Gray')
D) All of the above statements are true.
A) A format string may contain multiple placeholders, in which case the format method's arguments correspond to the placeholders from left to right: '{} {}'.format('Amanda', 'Cyan')
B) The format string can reference specific arguments by their position in the format method's argument list, starting with position 0, as in: '{0} {0} {1}'.format('Happy', 'Birthday')
You can reference each argument as often as you like and in any order.
C) You can reference keyword arguments by their keys in the placeholders, as in: '{first} {last}'.format(first='Amanda', last='Gray')
'{last} {first}'.format(first='Amanda', last='Gray')
D) All of the above statements are true.
Unlock Deck
Unlock for access to all 20 flashcards in this deck.
Unlock Deck
k this deck
16
Which of the following statements a), b) or c) is false?
A) When you read a sentence, your brain breaks it into individual words, or tokens, each of which conveys meaning.
B) Interpreters like IPython xe "tokenization"tokenize statements, breaking them into individual components such as keywords, identifiers, operators and other elements of a programming language.
C) Tokens typically are separated by xe "whitespace character"whitespace characters such as blanks, tabs and newlines, though other characters may be used-the separators are known as delimiters.
D) All of the above statements are true.
A) When you read a sentence, your brain breaks it into individual words, or tokens, each of which conveys meaning.
B) Interpreters like IPython xe "tokenization"tokenize statements, breaking them into individual components such as keywords, identifiers, operators and other elements of a programming language.
C) Tokens typically are separated by xe "whitespace character"whitespace characters such as blanks, tabs and newlines, though other characters may be used-the separators are known as delimiters.
D) All of the above statements are true.
Unlock Deck
Unlock for access to all 20 flashcards in this deck.
Unlock Deck
k this deck
17
Which of the following statements is false?
A) String method split with no arguments tokenizes a string by breaking it into substrings at each whitespace character, then returns a list of tokens.
B) To tokenize a string at a custom delimiter (such as each comma-and-space pair), specify the delimiter string (such as, ', ') that split uses to tokenize the string, as in: letters = 'A, B, C, D'
Letters.split(', ')
C) If you provide an integer as split's second argument, it specifies the maximum number of splits. The last token is the remainder of the string after the maximum number of splits. Assuming the string in Part (b), the code letters.split(', ', 1)
Returns
['A', 'B', 'C, D']
D) There is also an rsplit method that performs the same task as split but processes the maximum number of splits from the end of the string toward the beginning.
A) String method split with no arguments tokenizes a string by breaking it into substrings at each whitespace character, then returns a list of tokens.
B) To tokenize a string at a custom delimiter (such as each comma-and-space pair), specify the delimiter string (such as, ', ') that split uses to tokenize the string, as in: letters = 'A, B, C, D'
Letters.split(', ')
C) If you provide an integer as split's second argument, it specifies the maximum number of splits. The last token is the remainder of the string after the maximum number of splits. Assuming the string in Part (b), the code letters.split(', ', 1)
Returns
['A', 'B', 'C, D']
D) There is also an rsplit method that performs the same task as split but processes the maximum number of splits from the end of the string toward the beginning.
Unlock Deck
Unlock for access to all 20 flashcards in this deck.
Unlock Deck
k this deck
18
Which of the following statements a), b) or c) is false?
A) Strings support many of the same sequence operations as sets, lists and tuples.
B) Strings, like tuples, are xe "immutable:string"immutable.
C) The xe "re module"re module can be used to match patterns in text.
D) All of the above statements are true.
A) Strings support many of the same sequence operations as sets, lists and tuples.
B) Strings, like tuples, are xe "immutable:string"immutable.
C) The xe "re module"re module can be used to match patterns in text.
D) All of the above statements are true.
Unlock Deck
Unlock for access to all 20 flashcards in this deck.
Unlock Deck
k this deck
19
Which of the following statements a), b) or c) is false?
A) String method partition splits a string into a tuple of three strings based on the method's separator argument. The three strings are the part of the original string before the separator, the separator itself, and the part of the string after the separator.
B) Consider a string representing a student's name and grades: 'Amanda: 89, 97, 92'
The following code splits the original string into the student's name, the separator ': ' and a string representing the list of grades:
'Amanda: 89, 97, 92'.partition(': ')
C) To search for the separator from the end of the string instead, use method rpartition to split. For example, consider the following URL string: url = 'http://www.deitel.com/books/PyCDS/table_of_contents.html'
The following call to rpartition splits 'table_of_contents.html' from the rest of the URL:
Rest_of_url, separator, document = url.rpartition('/')
D) All of the above statements are true.
A) String method partition splits a string into a tuple of three strings based on the method's separator argument. The three strings are the part of the original string before the separator, the separator itself, and the part of the string after the separator.
B) Consider a string representing a student's name and grades: 'Amanda: 89, 97, 92'
The following code splits the original string into the student's name, the separator ': ' and a string representing the list of grades:
'Amanda: 89, 97, 92'.partition(': ')
C) To search for the separator from the end of the string instead, use method rpartition to split. For example, consider the following URL string: url = 'http://www.deitel.com/books/PyCDS/table_of_contents.html'
The following call to rpartition splits 'table_of_contents.html' from the rest of the URL:
Rest_of_url, separator, document = url.rpartition('/')
D) All of the above statements are true.
Unlock Deck
Unlock for access to all 20 flashcards in this deck.
Unlock Deck
k this deck
20
Consider this text from Shakespeare's Romeo and Juliet: soliloquy = 'To be or not to be, that is the question'
Which of the following statements a), b) or c) is false?
A) String method index searches for a substring within a string and returns the first index at which the substring is found; otherwise, a xe "ValueError exception"ValueError occurs. The following code returns 3: soliloquy.index('be')
B) String method rindex performs the same operation as index, but searches from the end of the string and returns the last index at which the substring is found; otherwise, a xe "ValueError exception"Value-Error occurs. The following code returns 3: soliloquy.rindex('be')
C) String methods find and rfind perform the same tasks as index and rindex but, if the substring is not found, return -1 rather than causing a xe "ValueError exception"Value-Error.
D) All of the above statements are true.
Which of the following statements a), b) or c) is false?
A) String method index searches for a substring within a string and returns the first index at which the substring is found; otherwise, a xe "ValueError exception"ValueError occurs. The following code returns 3: soliloquy.index('be')
B) String method rindex performs the same operation as index, but searches from the end of the string and returns the last index at which the substring is found; otherwise, a xe "ValueError exception"Value-Error occurs. The following code returns 3: soliloquy.rindex('be')
C) String methods find and rfind perform the same tasks as index and rindex but, if the substring is not found, return -1 rather than causing a xe "ValueError exception"Value-Error.
D) All of the above statements are true.
Unlock Deck
Unlock for access to all 20 flashcards in this deck.
Unlock Deck
k this deck