Reputation: 65
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)?
Upvotes: 3
Views: 2986
Reputation: 51
def first_half(str):
calc = len(str) / 2
if calc:
return str[:calc]
else:
if len(str) <= 0:
return str
first_half('abcdef')
Upvotes: 0
Reputation: 559
Here is the most simple and straight-forward solution.
Running until the middle of the string, here, //
is used to confirm that I am getting only int values after dividing, in case the length is odd.
def first_half(str):
return str[:(len(str)//2)]
Upvotes: 2
Reputation: 744
In python:
return str[0: int(len( str )/2)];
here no need to check whether it's even or odd lenght. len( str )/2
will round itself.
Answered following before question re-edit:
In Javascript:
var str = "WooHoo";
if (str.length%2 == 0) {
console.log(str.substr(0, str.length / 2));
}
Answer is Woo
.
Or just use:
str.substr(0, str.length / 2);
No need to check if (str.length%2 == 0)
.
Other languages have the length
property, and substring
function too.
Upvotes: 3
Reputation: 542
Are you looking for something like this:
def first_half(str):
if len(str) % 2 == 0:
return str[:len(str) // 2]
or maybe like this?
def first_half(str):
return str[:len(str) // 2 if len(str) % 2 == 0 else 0]
This is quite vague as you haven't explained what to do when an uneven length string is provided.
Upvotes: 1