Reputation: 35
So basically I have to make a code that inverts every odd letter of a string. I got a fair way, but couldn't figure out how to put the string back together properly.
So the output should be 'hlleo', but instead i get 'hloe'. How do i fix this?
Input is hello
Expected output is hlleo
Output is hloe
word = 'hello'
output = ''
value = -1
word1 = word[0::2]
word2 = word[1::2]
word2 = word2[::-1]
print(word2)
print(word1)
for letter in word2:
value += 2
output = word1[:value] + letter + word1[value:]
print(output)
print('Correct output should be "hlleo"')
Upvotes: 0
Views: 257
Reputation: 9437
def revodd(s):
l = list(s)
l[1::2] = reversed(l[1::2])
return "".join(l)
Convert to a list of strings (because lists are mutable and strings aren't), set a slice of the odd indices to a reversed version of itself, and join
the list back into a string. I see @schwobaseggl has done the reverse with a slice, but I think using reversed
is much more readable.
Test cases:
In [23]: revodd("0123456789")
Out[23]: '0927456381'
In [24]: revodd("012345678")
Out[24]: '072543618'
In [25]: revodd("hello")
Out[25]: 'hlleo'
Upvotes: 0
Reputation: 514
Unless I have misunderstood your question, this can only 'work properly' with odd length strings so that the odd indexed characters are all swapping with other odd indexed characters.
def invert_odds(string):
# Get reverse of string
reverse = string[::-1]
new_string = ""
# Make new string with chars from either original or reversed
# strings depending on index
for i in range(len(string)):
if i % 2 == 0:
new_string += string[i]
else:
new_string += reverse[i]
return new_string
Upvotes: 0
Reputation: 43534
Here's a one liner.
inv_word = "".join([word[i] if i%2==0 else word[len(word)-(i+1)] for i in range(len(word))])
The logic here is that we build a new list of characters by iterating over the word. If the index is even (i%2==0
), then we use the corresponding index in the word. Otherwise, we use the inverted character which is found at index len(word)-(i+1)
.
At the end, join the list together with "".join()
to make it a string.
Upvotes: 0
Reputation: 73480
You can turn the string into a list
and use slice assignment and join
it back together:
w = 'abcdef'
l = list(w)
l[1::2] = l[1::2][::-1]
w2 = ''.join(l)
# 'afcdeb'
Upvotes: 0
Reputation: 7261
This works:
In [6]: word = 'hello'
In [7]: dorw = list(reversed(word))
In [8]: new_word = ''
In [9]: for i in range(len(word)):
...: w = word[i]
...: if i % 2 != 0:
...: w = dorw[i]
...: new_word += w
...:
In [10]: new_word
Out[10]: 'hlleo'
Based on index i
a word is taken either from the real "word" or the reversed version of it.
Upvotes: 2