Python (almost fine): string splitter

Viewed 106

I'm doing a lab to split an odd string and print out first half, middle char, second half. Code is working fine, except I can't get rid of the middle char when printing out the second half. Here it is:

str = input("Enter an odd length string: ")
length = len(str)
middle = length // 2
half1 = str[ : middle ]
half2 = str[middle : ]
print("Middle character:",str[middle])
print("First half:",half1)
print("Second half:",half2)

The result is:

Enter an odd length string: Fortune favors the bold
Middle character: o
First half: Fortune fav
Second half: ors the bold

It is wrong because of that 'o'...

Any clues?

Thanks a lot.

2 Answers

Start the second half after the middle char as you don't want it there

half2 = value[middle + 1:]

In case you need to handle even length too

def string_splitter(value):
    length = len(value)
    middle = length // 2
    half1 = value[: middle]
    half2 = value[middle:]

    if length % 2 == 1:
        half2 = value[middle + 1:]
        print("Middle character:", value[middle])

    print("First half:", half1)
    print("Second half:", half2)

this is the correct half2:

half2 = str[middle+1:]

with ABCDE as input:

string ='ABCDE'
length = len(string) # 5
middle = length // 2 # 2
half1 = string[:middle] # AB
half2 = string[middle+1:] # DE
middle_charachter = string[middle] # C
Related