Input:- 'peter piper picked a peck of pickled peppers.'
Output:- 'peppers. pickled of peck a picked piper peter'
can anyone help this problem
CodePudding user response:
In the following
sis the string'peter piper picked a peck of pickled peppers.';s.split()returns a list of the "words" in the stringswhere "words" are separated by whitespace:['peter', 'piper', 'picked', 'a', 'peck', 'of', 'pickled', 'peppers.'](docs);reversed(s.split())returns a reverse iterator over the lists.split()(docs);next(it).rstrip('.')returns the first element in the iterator, stripping the period from this element:'peppers'(docs); we print this out (without ending the print with a newline, whichprintdoes by default);- we loop over the remaining elements in the iterator, printing them out (preceded by a space character and without ending the print with a newline).
s = 'peter piper picked a peck of pickled peppers.'
it = reversed(s.split())
print(next(it).rstrip('.'), end = "")
for i in it:
print(f" {i}", end = "")
print('.')
Output
peppers pickled of peck a picked piper peter.
CodePudding user response:
Split, reverse and join:
s = 'peter piper picked a peck of pickled peppers.'
print(' '.join(reversed(s.split())))
CodePudding user response:
sentence = "peter piper picked a peck of pickled peppers."
#split string by single space
chunks = sentence.split(' ')
s = " "
rev = s.join(reversed(chunks))
print(rev)
Hope this helps
