我正在尝试对字符串进行切片并将组件插入列表(或索引,集合或任何东西)中,然后进行比较,这样
I am trying to slice a string and insert the components into a list (or index, or set, or anything), then compare them, such that
输入:
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 是整数.
However, the built-in slice command [:i] specifies that i be an integer.
我该怎么办?
推荐答案您始终可以做到这一点.
You can always do that..
word = "spamspamspam" first_half = word[:len(word)//2] second_half = word[len(word)//2:]对于任何字符串 s 和任何整数 i , s == s [:i] + [:i] 是不变的.请注意,如果 len(word)是奇数,则在第二个一半"中您将获得比第一个更多的字符.
For any string s and any integer i, s == s[:i] + [:i] is invariant. Note that if len(word) is odd, you will get one more character in the second "half" than the first.
如果您使用的是python 3,请使用 input 而不是 raw_input .
If you are using python 3, use input as opposed to raw_input.
更多推荐
使用变量动态切片字符串
发布评论