-2

Hi I am learning python I was just trying to resolve the above example.That is make a function to change the string "oalalaeah" to "hello". Notice that 'hello' is the alternate letter starting from the back. I can do both individually. Important: I want to do it using only python functions()

`def rev_str(str1):
    new_str = ''
    index = len(str1)
    while index > 0:
        new_str += str1[index-1]
        index = index - 1
    return new_str`
print(rev_str('oalalaeah'))

to reverse the string to "haealalao"

later use:

def rev_alt(str2):
    fin_str = ''
    index = -2
    while index < len(str2)-1:
        fin_str += str2[index+2]
        index = index + 2
    return fin_str

print(rev_alt('haealalao'))

This gives me "hello" but these are 2 separate operations. I want to have 1 function that that will turn "oalalaeah" to "hello". I am sorry if this is too easy. Its driving me crazy

Samir Tendulkar
  • 63
  • 1
  • 2
  • 11

1 Answers1

2
def rev_str(str1):
    new_str = ''
    index = len(str1)
    while index > 0:
        new_str += str1[index-1]
        index = index - 1
    return new_str

This is taking each letter in the string from the end to the beginning by decreasing the index by one on each iteration. Literally the only change needed to take every second letter is to decrease the index by two on each iteration:

def rev_str(str1):
    new_str = ''
    index = len(str1)
    while index > 0:
        new_str += str1[index-1]
        index = index - 2  #  here
    return new_str

print(rev_str('oalalaeah'))  # hello

The pythonic version of this is the built-in slice syntax:

print('oalalaeah'[::-2])  # hello
deceze
  • 510,633
  • 85
  • 743
  • 889