Chapter 8
If a string has 10 characters, what is the index of the last character?
9
The isupper method converts a string to all uppercase characters.
False It checks if it's upper.
What happens if you try to use an invalid index to access a character in a string?
IndexError: string index out of range
This is the last index in a string.
The size of the string minus one
You can use the loop to iterate over the individual characters in a string.
True
Once a string is created, it cannot be changed.
True Strings are immutable
What does the following code display? mystr='abc'*3 print(mystr)
abcabcabc
This will happen if you try to use an index that is out of range for a string.
an IndexError exception will occur
This is the first index in a string. a. - 1 b. 1 c. 0 d. The size of the string minus one
c. 0
What will the following code display? mystring='abcdefg' print(mystring[2:5])
cde
This function returns the length of the string
len
Write a program that reads a string from the user containing a date in the form mm/dd/yyyy should print the date in the form March 12, 2012.
month=['January','February','March','April','May','June','July','August','September','October','November','December'] strdate=input('Enter a data in form of mm/dd/yyyy:') datelist=strdate.split('/') newdate=month[int(datelist[0])-1]+' ' newdate += datelist[1]+',' newdate+=datelist[2] print(newdate)
Write a loop that counts the number of digits that appear in the string referenced by mystring.
mystring='One:1 Two:2 Three:3' digit_count=0 for digit in mystring: if digit.isdigit(): digit_count+=1: print(digit_count)
Write a loop that counts the number of lowercase characters that appear in the string referenced by mystring.
mystring='One:1 Two:2 Three:3' count=0 for lcc in mystring: if lcc.islower(): count +=1; print(count) output: 8
Write a loop that counts the # of space characters that appear in the string referenced by mystring
mystring='Sunday Monday Tuesday Wednesday' space_count=0 for space in mystring: if space == ' ': space_count += 1 print(space_count) OUTPUT: 3
Write a program that asks the user to enter a series of single-digit numbers with nothing separating them. The program should display the sum of all the single digit numbers in the string. ex: input:2514 output: 12
strdigit=input('Enter number: ') length = len(strdigit) i=0 sum=0 while i<length: if strdigit[i].isdigit(): sum+=int(strdigit[i]) else: break if i==length: print('The sum of digits is sum:', sum) else: print('Series is not valid')
What does the following code display? mystr = "yes" mystr += "no" mystr += "yes" print(mystr)
yesnoyes