Return middle part of string

前端 未结 2 1069
眼角桃花
眼角桃花 2021-01-24 12:49

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

相关标签:
2条回答
  • 2021-01-24 13:05

    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"))
    
    0 讨论(0)
  • 2021-01-24 13:07

    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'}
    
    0 讨论(0)
提交回复
热议问题