Python字符串切片

2024-06-28 23:57:25 发布

您现在位置:Python中文网/ 问答频道 /正文

代码:

count = 0
oldcount = 0
for char in inwords:
    if char == " ":
        anagramlist.append(inwords[oldcount, count])
        oldcount = count
        count = 0
    else:
        count += 1

错误:

^{pr2}$

到底怎么回事? count和oldcount显然是int,但是错误消息说它们不是

我甚至会写字

anagramlist.append(inwords[int(oldcount), int(count)])

得到同样的错误


Tags: 代码in消息forifcount错误else
3条回答

你只是想做anagramlist = inwords.split()
如果您真的想手动切片,则必须使用:

anagramlist.append(inwords[oldcount:count+oldcount])

切片语法有误。代码:

inwords[oldcount, count]

解析方式与:

^{pr2}$

不是从oldcount切片到count,而是创建一个oldcount和{}的元组并将其用作字符串索引。在

正确的Python切片语法是:

inwords[oldcount:count]

您试图使用(oldcount, count)作为列表的索引。这是元组,不是整数

你的意思是:

anagramlist.append(inwords[oldcount:count])

是吗?在

相关问题 更多 >