简体   繁体   中英

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])

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:])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM