Home > other >  Reverse String but forward way in python
Reverse String but forward way in python

Time:05-03

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

  • s is the string 'peter piper picked a peck of pickled peppers.'.
  • s.split() returns a list of the "words" in the string s where "words" are separated by whitespace: ['peter', 'piper', 'picked', 'a', 'peck', 'of', 'pickled', 'peppers.']
  • reversed(s.split()) returns a reverse iterator over the list s.split().
  • next(it).rstrip('.') returns the first element in the iterator, stripping the period from this element: 'peppers'. We print this out (without ending the print with a newline, which print does 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, which print does by default).
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:

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

  • Related