簡體   English   中英

錯誤; 字符串索引必須是整數,很確定這些值是整數

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

賦值就是寫一段代碼,返回字符串的后半部分。 得到一個錯誤說索引必須是整數,但我似乎無法弄清楚問題出在哪里。感謝幫助

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

你錯誤地使用了切片。 看看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