Search code examples
pythonstringstring-length

Need more elegant solution to even string length


Here's the task I got:

Given a string of even length, return the first half. So the string "WooHoo" yields "Woo".

first_half('WooHoo') → 'Woo'
first_half('HelloThere') → 'Hello'
first_half('abcdef') → 'abc'

Here's my solution:

def first_half(str):
    if len(str) % 2 == 0:
        b = len(str) // 2
        return str[:b]

My question is:

Can you show me a simpler solution in Python of course that doesn't require me to use a variable for half of the string length (b)?


Solution

  • In python:

    str = "WooHoo"   
    str = str[:-len(str)/2]