使用variab动态切片字符串

2024-10-02 22:27:07 发布

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

我试图分割一个字符串并将组件插入到列表(或索引、集合或任何内容)中,然后比较它们,以便

输入:

abba

输出:

['ab', 'ba']

给定输入的可变长度。

所以如果我切一根绳子

word = raw_input("Input word"
slicelength = len(word)/2
longword[:slicelength]

如此

    list = [longwordleftslice]
    list2 = [longwordrightslice]

    list2 = list2[::-1 ] ## reverse slice
    listoverall = list + list2

但是,内置的slice命令[:i]指定i为整数。

我能做什么?


Tags: 字符串内容列表inputrawab组件slice
2条回答

你可以一直这么做。。

word = "spamspamspam"
first_half = word[:len(word)//2]
second_half = word[len(word)//2:]

对于任何字符串s和任何整数is == s[:i] + [:i]都是不变的。请注意,如果len(word)是奇数,那么在第二个“半”字符中将比第一个多出一个字符。

如果您使用的是python 3,请使用input,而不是raw_input

我猜你在用Python 3。使用//而不是/。在Python 3中,/总是返回一个列表不喜欢的float//返回一个int,截断超过小数点的所有内容。

然后你要做的就是在中点前后切片。

>>> a = [0, 1, 2, 3, 4]
>>> midpoint = len(a) // 2
>>> a[:midpoint]
[0, 1]
>>> a[midpoint:]
[2, 3, 4]

相关问题 更多 >