Return middle part of string

前端 未结 2 1088
眼角桃花
眼角桃花 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: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'}
    

提交回复
热议问题