Python: How do I reverse every character in a string list? [duplicate]

北战南征 提交于 2019-12-25 00:36:44

问题


For instance, myList = ['string1', 'string2', 'string3']... now I want my result to be this:

 ['1gnirts', '2gnirts', '3gnirts']

I've found few examples on how to reverse strings in general but not specific to this problem ... I'm bit confused on how to do a reverse of strings that are in a list.


回答1:


reversed_strings = [x[::-1] for x in myList][::-1]



回答2:


There are two things you need to use, the reverse function for lists, and the [::-1] to reverse strings. This can be done as a list comprehension as follows.

myList.reverse
newList = [x[::-1] for x in myList]



回答3:


Or

oneShot = [x[::-1] for x in myList][::-1]




回答4:


If you already know how to reverse a single word, for this problem you only have to do the same for each of the words of the list:

def reverseWord(word):
    # one way to implement the reverse word function
    return word[::-1]

myList = ["string1", "string2", "string3"]

# apply the reverseWord function on each word using a list comprehension
reversedWords = [reverseWord(word) for word in myList]


来源:https://stackoverflow.com/questions/48952467/python-how-do-i-reverse-every-character-in-a-string-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!