MrG MrG - 6 days ago 5
Python Question

Reverse string without reverse function

For an input text I have to count all the vowels, capitalize first letter in each word and output text in reverse(doesn't have to be capitalized), without using title or reverse functions. I was able to figure out the count for vowels, but struggling with other two.

def main():

vowelCount = 0
text = 'abc'

while(len(text) != 0):
text = input('Please etner some text or press <ENTER> to exit: ')

for char in text:
if char in 'aeiouAEIOU':
vowelCount += 1
print('Vowels:', vowelCount)
vowelCount = 0



for i in text:
i = text.find('') + 1
print(i)

print(text[0].upper() + text[1:])


main()

Answer

Here are two examples of reversing a string. Slice the string

>>> s = 'hello'
>>> reversed_s = s[::-1]

Or with a loop.

res = ''
for char in s:
    res = char + res

Full Code

def main():
    # Run infinitely until break or return
    # it's more elegant to do a while loop this way with a condition to
    # break instead of setting an initial variable with random value.
    while True:
        text = input('Please enter some text or press <ENTER> to exit: ')
        # if nothing is entered then break
        if not text:
            break

        vowelCount = 0
        res = ''
        prev_letter = None

        for char in text:
            if char.lower() in 'aeiou':
                vowelCount += 1
            # If previous letter was a space or it is the first letter
            # then capitalise it.
            if prev_letter == ' ' or prev_letter is None:
                char = char.upper()

            res += char # add char to result string
            prev_letter = char # update prev_letter

        print(res) # capitalised string
        print(res[::-1]) # reverse the string
        print('Vowel Count is: {0}'.format(vowelCount))

# Example
Please enter some text or press <ENTER> to exit: hello world!
Hello World!
!dlroW olleH
Vowel Count is: 3
Comments