[英]What is the most pythonic way to re-order letters in a string?
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? 但是,是否可以用更Python化的方式编写字符串中元素的重排? 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? 这又是我想要实现的目标,但是例如,我是否仍可以以更pythonic的方式编写切片和添加行,而无需至少显式执行添加操作?
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! 谢谢!
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. 为了使字符串中没有空格的单词反向,我们还需要知道单词在何处被拆分,为此我们需要一个列表。 eg for
HelloWorldThisIsMe
, that that list will be [0,5,10,14,16,18]
例如对于
HelloWorldThisIsMe
,该列表将为[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
We can also achieve the same result in this way: 我们还可以通过这种方式获得相同的结果:
s = "Hello World!"
rev = ' '.join(s.split(' ')[-1::-1])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.