【问题标题】:Error; String indices must be integers, pretty sure the values ARE integers错误;字符串索引必须是整数,很确定值是整数
【发布时间】:2020-06-18 13:33:27
【问题描述】:

赋值是写一段代码,返回一个字符串的后半部分。说索引必须是整数时出现错误,但我似乎无法弄清楚问题出在哪里。感谢您的帮助

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

【问题讨论】:

  • 我认为string_length / 2 应该是string_length % 2。您正在测试它是偶数还是奇数,对吗?
  • elif 条件与if 条件完全相反时,您应该使用else:
  • 请提供完整的错误信息,以及minimal reproducible example
  • 顺便说一句,为什么函数打印而不是返回结果?

标签: python python-3.x string indices


【解决方案1】:

您错误地使用了切片。看看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:])

【讨论】:

  • 你太棒了,谢谢
  • 如果有帮助,请接受我的回答(绿色勾号按钮)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-12-11
  • 2014-12-30
  • 2020-08-09
  • 2020-08-28
  • 2019-04-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多