Reputation: 884
I want to take a string and change the order of the letters in the string.
I can achieve this via the following code:
s = 'Hello World!'
s = s[6:] + s[5:6] + s[:5]
s
This produces the ouput:
'World! Hello'
This is what I want to achieve.
However, is it possible to write the rearranging of the elements from the string in a more pythonic way? For example, without having to slice and add, but specify which slice 'goes where' in the reformulation somehow.
Thanks!
Later Edit:
Specifically I want to achieve this absent the space being between the words. For example:
s = 'HelloWorld!'
s = s[5:] + s[:5]
s
This produces the output:
'World!Hello'
This is again what I would want to achieve, but can I write the slicing and adding line in a more pythonic way still, for example, without needing to perform the add explicitly at least?
Note: I want to be able to explicitly specify where the slice will happen using the index of the element and switch the position of the two slices.
So it might also be:
s = 'HelloWorld!'
s = s[6:] + s[:6]
s
This produces the output:
'orld!HelloW'
Thanks!
Upvotes: 0
Views: 160
Reputation: 20500
Split the string into a list of words, reverse that list, and join the list back to a string
s = "hello world"
li = reversed(s.split())
res = ' '.join(li)
The output will be
world hello
Or we can do all of this in one line
s = "hello world"
res = ' '.join(reversed(s.split()))
In order to reverse words in a string without spaces, we also need to know where the words are split, and we need a list for that.
e.g for HelloWorldThisIsMe
, that that list will be [0,5,10,14,16,18]
So the new code will split words according to the indexes, reverse the list and join the list to a string back together
def reorder(indexes, s):
res = [s[indexes[idx]:indexes[idx+1]] for idx in range(len(indexes)-1)]
return ''.join(reversed(res))
print(reorder([0,5,10,14,16,18],'HelloWorldThisIsMe'))
#MeIsThisWorldHello
print(reorder([0,5,11],'HelloWorld!'))
#World!Hello
Upvotes: 1
Reputation: 8709
We can also achieve the same result in this way:
s = "Hello World!"
rev = ' '.join(s.split(' ')[-1::-1])
Upvotes: 0