简体   繁体   English

错误; 字符串索引必须是整数,很确定这些值是整数

[英]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/看看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:])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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