Dynamically Slice A String Using A Variable
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 variabl
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]
Post a Comment for "Dynamically Slice A String Using A Variable"