Dynamically slice a string using a variable
Solution 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
.
Solution 2
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]
Christopher W
Updated on June 04, 2022Comments
-
Christopher W almost 2 years
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 thati
be an integer.What can I do?
-
wim about 12 yearsthis was my first guess too, but then they wouldn't be using
raw_input
right.. ? -
senderle about 12 years@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 aTypeError
from the above code, other than true division.