I have to return the middle part of string. When the string has odd number of elements, the middle part is one letter and when the string has even number of elements, the middle
The issue is your code, as written, always accesses a location in the string. You can add a check for this exception.
def middle(s):
if len(s) == 0:
return ""
elif len(s) % 2 != 0:
return s[len(s)//2]
elif len(s) % 2 == 0:
return s[len(s)//2 - 1] + s[len(s)//2]
print(middle(""))
Alternatively, you could make your code more condensed with:
def middle(s):
offset = len(s)%2==0
return s[len(s)//2-offset:round(len(s)/2)+offset]
print(middle("helloworld"))
You are close; however, you need list slicing for the even case:
s = ["help", "hi", "hey"]
new_s = [i[len(i)//2] if len(i)%2 != 0 else i[(len(i)//2)-1:(len(i)//2)+1] for i in s]
Output:
['el', 'hi', 'e']
To view the pairings:
new_s = dict(zip(s, [i[len(i)//2] if len(i)%2 != 0 else i[(len(i)//2)-1:(len(i)//2)+1] for i in s]))
Output:
{'hi': 'hi', 'help': 'el', 'hey': 'e'}