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?

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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]

2 Comments

this was my first guess too, but then they wouldn't be using raw_input right.. ?
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.