Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)?

like image 478
noob81 Avatar asked Nov 26 '25 20:11

noob81


1 Answers

In python:

str = "WooHoo"   
str = str[:-len(str)/2]
like image 139
Nolin M. Avatar answered Nov 29 '25 09:11

Nolin M.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!