Write a program that accepts a sentence from the user on a single line, and which outputs the number of words in the sentence. A sample execution appears as follows:
Enter a sentence: The quick brown fox jumps over the lazy dog You entered 9 words. |
Solution:
sentence = input('Enter a sentence: ')
k = len(sentence.split())
print('You entered', k, 'words.')
Write a program that prompts the user for a name that is
assumed to be of form
The precise format should match the following sample session.
What is your name? Elmer James Fudd Elmer J. Fudd |
Solution:
person = input('What is your name? ')
pieces = person.split()
print(pieces[0] + ' ' + pieces[1][0] + '. ' + pieces[2])
An alternate approach is to avoid the explicit split but to use index to find the locations of the two expected spaces, and then use slicing.
person = input('What is your name? ')
j = person.index(' ')
k = person.index(' ', j+1) # find second space
print(person[ :j+2] + '.' + person[k:])
Look carefully at the limits of the slices used to get all
relevant portions of the original text, as with