Sudha Singh
Sudha Singh

Reputation: 3

unable to get the expected answer for string palindrom

Every time i am geting else condition as true. If i pass input string as "ama" then code should give input string is palindrom. But i am getting string is not palindrom. Input: ami output: ami Expected:string is palindrom

Input: amit output: tima Expected:string is n palindrom

def str_rev (input_str):
    print("input_str:", input_str)
    rev_str = " "
        for i in (input_str):
            rev_str = i + rev_str
    print("inp_str:", input_str)    
    print("rev_str:", rev_str)
    if (input_str == rev_str):
        print("string is palindrom")
    else:
        print("string is not palindrom")
    return  rev_str       
        
str = input ("Enter the string:")
print("org string:", str)
final_str= str_rev (str)
print("reverse string:", final_str)

Upvotes: 0

Views: 32

Answers (3)

Jaroslav Petr
Jaroslav Petr

Reputation: 1

you got bug at line 3 rev_str = " " should be rev_str = "" #empty string

otherwise, you create a new string with empty space at the start Jarda

Upvotes: 0

GaryMBloom
GaryMBloom

Reputation: 5692

At a quick glance, your formatting is off, but I think your problem is with white space. Change:

rev_str = " "

to

rev_str = ""

to get rid of that extra white space.

In fact, you can trim your strings before comparing, with the .strip() command to remove any leading or trailing white space.

'  hi '.strip() --> 'hi'

Upvotes: 0

Trimonu
Trimonu

Reputation: 44

A palindrome is a word that is the same backwards and forwards. Therefore ami is not a palindrome.

Upvotes: 1

Related Questions