Search code examples
pythonpython-3.xstringindices

Error; String indices must be integers, pretty sure the values ARE integers


Assignment is to write a code that returns the second half of a string. Getting an error on this saying the indices must be integers, but I can't seem to figure out where the problem is.Help is appreciated

def last_half(sent):
    string_length = len(sent)
    if string_length / 2 == 0:
        s_half = int(string_length/2)
        print(sent[s_half,-1])
    elif string_length / 2 != 0:
        s_half = int(round(string_length/2))
        print(sent[s_half,-1])

Solution

  • You were using slicing wrongly. Have a look at https://www.pythoncentral.io/how-to-slice-listsarrays-and-tuples-in-python/

    def last_half(sent):
        string_length = len(sent)
        if string_length / 2 == 0:
            s_half = int(string_length/2)
            print(sent[s_half:])
        elif string_length / 2 != 0:
            s_half = int(round(string_length/2))
            print(sent[s_half:])