【发布时间】: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