def get_middle_character(odd_string):
variable = len(odd_string)
x = str((variable/2))
middle_character = odd_string.find(x)
middle_character2 = odd_string[middle_character]
return middle_character2
def main():
print('Enter a odd length string: ')
odd_string = input()
print('The middle character is', get_middle_character(odd_string))
main()
I need to figure out how to print the middle character in a given odd length string. But when I run this code, I only get the last character. What is the problem?
Should be like below:
i know its too late but i post my solution I hope it will be useful ;)
You need to think more carefully about what your code is actually doing. Let's do this with an example:
Let's say that we call
get_middle_character('hello')
, soodd_string
is'hello'
:Everything is OK so far.
This is the first thing that is obviously odd - why do you want the string
'2'
? That's the index of the middle character, don't you just want an integer? Also you only need one pair of parentheses there, the other set is redundant.Obviously you can't
str.find
the substring'2'
inodd_string
, because it was never there.str.find
returns-1
if it cannot find the substring; you should usestr.index
instead, which gives you a nice clearValueError
when it can't find the substring.Note that even if you were searching for the middle character, rather than the stringified index of the middle character, you would get into trouble as
str.find
gives the first index at which the substring appears, which may not be the one you're after (consider'lolly'.find('l')
...).As Python allows negative indexing from the end of a sequence,
-1
is the index of the last character.You could actually have simplified to
return odd_string[middle_character]
, and removed the superfluous assignment; you'd have still had the wrong answer, but from neater code (and withoutmiddle_character2
, which is a terrible name).Hopefully you can now see where you went wrong, and it's trivially obvious what you should do to fix it. Next time use e.g. Python Tutor to debug your code before asking a question here.
You need to simply access character based on index of string and string slicing. For example:
Explanation:
str[:n]
: returns string from 0th index ton-1
th indexstr[n]
: returns value at nth indexstr[n:]
: returns value from nth index till end of list