I have the following question:
Print a string which has the reverse order 'Python love We. Science Data love We'
So 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.
Is there a way to get the expected result?
CodePudding user response:
Can be done this way:
In [1]: s = "We love Data Science. We love Python"
In [2]: ". ".join(
[" ".join(reversed(item.split())) for item in reversed(s.split("."))]
)
Out[2]: 'Python love We. Science Data love We'
CodePudding user response:
Examples:
Input : "We love Python"
Output : "Python love We"
Input : "We love Data Science"
output : "Science Data love We"
reverse the words in the given string program
string = "We love Python"
s = string.split()[::-1]
l = []
for i in s:
l.append(i)
print(" ".join(l))
or more simplest code:
string = "We love Python"
print(" ".join(string.split()[::-1]))
output:
Python love We
CodePudding user response:
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]]))