我正在尝试对字符串进行切片并将组件插入到列表(或索引、集合或任何内容)中,然后比较它们,这样
输入:
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
但是,内置切片命令[:i]
指定i
是一个整数。
我能做什么?
最佳答案
你总是可以做到这一点..
word = "spamspamspam"
first_half = word[:len(word)//2]
second_half = word[len(word)//2:]
对于任何字符串s
和任何整数i
,s == s[:i] + [:i]
是不变的。请注意,如果 len(word)
为奇数,则第二个“一半”中将比第一个“半”多一个字符。
如果您使用的是 python 3,请使用 input
而不是 raw_input
。
关于python - 使用变量动态切片字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9388993/