views:

252

answers:

3
+1  Q: 

reverse the string

I have a content of strings and I have to reverse the order using python. the content is

  1. Python
  2. Java
  3. microsoft
+20  A: 

If you want a new list:

a = ["Python", "Java", "Microsoft"]
b = a[::-1]
# b is now ["Microsoft", "Java", "Python"]

or

a = ["Python", "Java", "Microsoft"]
b = list(reversed(a))
# b is now ["Microsoft", "Java", "Python"]

If you want to modify an existing list:

a = ["Python", "Java", "Microsoft"]
a.reverse()
# a is now ["Microsoft", "Java", "Python"]

If you want a list where each of the individual strings has had its characters reversed:

a = ["Python", "Java", "Microsoft"]
b = [x[::-1] for x in a]
# b is now ["nohtyP", "avaJ", "tfosorciM"]

The reason why using slice notation with a[::-1] returns a sequence that is the reverse of a is because slice notation works like this:

sequence[start:end:step]

since you specify step to be -1, that means that it works backwards through the sequence one by one, which is in effect the reverse of the sequence. (start and end being omitted uses their default values, i.e. the entire sequence.)

Amber
Actually, reversed returns a generator; you'll need to use list(reversed(a))
chrispy
really complete response +
DrFalk3n
@chrispy thanks for the catch, updated.
Amber
-1: Way too complete for answering someone else's homework for them.
S.Lott
@S.Lott: The way I see it, this is a basic enough question that it deserves to be answered in a way that promotes exploration if the person in question is actually interested in learning. If they're not interested in learning, answering a simple question like this for them is not going to help them in the long run, so it won't really make a difference.
Amber
What is the default value for the end index? Running 'python'[5:0:-1] only returns 'nohty' without the 'p'?! The only value for end I found to get the full string was -6 or smaller. Any clarification?
Roland
To specify the extreme values, you can just omit them - the default values are the extreme beginning and extreme ending positions.
Amber
+1  A: 
>>> l = ["Microsoft", "Java", "Python"]
>>> l.reverse()
>>> l
['Python', 'Java', 'Microsoft']
>>>
Nick D
+1  A: 

the most comprehensible option for sequences is to use "reversed", but the result is always a list, so for a string you could either use it and convert it to a string again by joining the elements, or use a slice with negative index (this later being more efficient, I guess):

s = "abcd"
reversed(s) #-> ['d','c','b','a']
"".join(_) #-> 'dcba'

#or

s[::-1] #-> 'dcba'
fortran
Everytime I see that slice method it makes me warm and fuzzy inside. So elegant!
Dominic Bou-Samra