2

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

Input:

abba

Output:

['ab', 'ba']

Given a variable length of the input.

So if I slice a string

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

such that

    list = [longwordleftslice]
    list2 = [longwordrightslice]

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

However, the built-in slice command [:i] specifies that i be an integer.

What can I do?

Christopher W
  • 139
  • 2
  • 2
  • 8

2 Answers2

1

You can always do that..

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

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.

If you are using python 3, use input as opposed to raw_input.

wim
  • 338,267
  • 99
  • 616
  • 750
1

I'm guessing you're using Python 3. Use // instead of /. In Python 3, / always returns a float, which lists don't like. // returns an int, truncating everything past the decimal point.

Then all you have to do is slice before and after the midpoint.

>>> a = [0, 1, 2, 3, 4]
>>> midpoint = len(a) // 2
>>> a[:midpoint]
[0, 1]
>>> a[midpoint:]
[2, 3, 4]
senderle
  • 145,869
  • 36
  • 209
  • 233
  • 1
    this was my first guess too, but then they wouldn't be using `raw_input` right.. ? – wim Feb 22 '12 at 04:23
  • @wim, that's true. But fortunately `//` works in either case. In any case, I can't imagine a reason why the OP would be getting a `TypeError` from the above code, other than true division. – senderle Feb 22 '12 at 14:02