Zack Walton
Zack Walton

Reputation: 1

Reversing characters in a python string

I'm having trouble how to figure out how to just reverse a few words in a python string.

ex:

aString = "This is my string."

I know how to reverse the whole string, but I can't figure out how to reverse only a few words such as:

I need to reverse every word at an even index, 2, 4, 6, 8, 10, 12

aString = "This si my gnirts"

Upvotes: 0

Views: 200

Answers (3)

slearner
slearner

Reputation: 672

If you want to do it in one line...

out = ' '.join([x[::-1] if input.index(x)%2 == 1 else x for x in input.split(' ')])

EXAMPLE:

>>> input = 'here is an example test string'
>>> out = ' '.join([x[::-1] if input.index(x)%2 == 1 else x for x in input.split(' ')])
>>> out
'here si an elpmaxe tset string'

NOTE: I know you said that you were looking to reverse even indices in you original question, but it looked like you were actually looking for odd ones based on your example. Just switch the mod to %2==0 if I'm wrong about that.

Upvotes: 0

Moses Koledoye
Moses Koledoye

Reputation: 78536

You can use enumerate to generate indices alongside the items after splitting with str.split and reverse those at odd (not even since counting starts from zero) indices. Use str.join to rebuild the string:

>>> s = "This is my string"
>>> ' '.join(x if i%2==0 else x[::-1] for i, x in enumerate(s.split()))
'This si my gnirts'

Upvotes: 3

Lucas Crijns
Lucas Crijns

Reputation: 68

You can do this:

newString = []
for index, i in enumerate(aString.split()):
   if i % 2 == 0:
      newString.append(i[::-1])
   else:
      newString.append(i)
newString = ''.join(newString)

Upvotes: 1

Related Questions