Assignment:
Print a string which has the reverse order
'Python love We. Science Data love We'
I tried this:
strg = We love Data Science. We love Python
words = strg.split(" ")
words.reverse()
new_strg = " ".join(words)
print(new_strg)
>>> Python love We Science. Data love We
But the answer isn't as expected because the .
after Science
is not at the proper place.
How to get the expected result?
Is this the output you need?
Python love We. Science Data love We
Then the code is
strg = 'We love Data Science. We love Python'
pos = len(strg) - strg.index('.') - 2
words = [e.strip('.') for e in strg.split()]
words.reverse()
new_strg = ' '.join(words)
print(new_strg[:pos] + '.' + new_strg[pos:])
Or another way to do it:
strg = 'We love Data Science. We love Python'
new_strg = [s.split()[::-1] for s in strg.split('.')][::-1]
print(' '.join(new_strg[0]) + '. ' + ' '.join(new_strg[1]))
#or
print('{}. {}'.format(' '.join(new_strg[0]), ' '.join(new_strg[1])))
Or to raise the bar:
strg = 'We love Data Science. We love Python'
print('. '.join([' '.join(new_strg.split()[::-1]) for new_strg in strg.split('.')[::-1]]))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With