Reputation: 1085
I have a certain string, or several strings. For example:
a = '12345678'
b = '123456789'
I'm using Python 3.2. I'm trying to get the last half of a string written on backwards. If a string has an odd amount of characters, the middle character is discarded. So, what I'm trying to achieve is:
a_out = '8765'
b_out = '9876'
The way I do it is the following:
a_back = a[::-1]
a_out = a_back[0:len(a_back)//2]
The question is: is there a shorter way to do this? Can it be done in one operation instead of two?
Upvotes: 2
Views: 787
Reputation: 58985
You can just make it a one-liner:
a_out = a[::-1][0:len(a)//2]
It would be nice if you could do fancy indexing in a string, like we do in a numpy
array, then another solution would be:
a_out = a[ range(len(a)-1, len(a)//2-1, -1) ] # NOT POSSIBLE
@jamylak suggested to use 'itemgetter' to accomplish an equivalent for fancy indexing in an efficient way:
from operator import itemgetter
items = [0,3,2,1,0,0,2,3,]
a_out = ''.join( itemgetter( *items )(a) )
#14321134
Upvotes: 1
Reputation: 43477
Using a method:
a = '12345678'
b = '123456789'
def method(x):
return x[:-(len(x)+1)//2:-1]
print method(a)
print method(b)
>>>
8765
9876
Upvotes: 1
Reputation: 18653
You can calculate the index and reverse the string at the same time:
>>> a[:-(len(a)+1)//2:-1]
'8765'
>>> b[:-(len(b)+1)//2:-1]
'9876'
Upvotes: 6