如何在python中使用切片运算符从中间部分提取字母?

时间:2015-05-12 13:45:29

标签: python list python-2.7 slice

我试图用所有可能性来理解下面的例子。

  +---+---+---+---+---+---+---+---+---+
  | C | O | M | P | U | T | E | R | S |
  +---+---+---+---+---+---+---+---+---+
  0   1   2   3   4   5   6   7   8   9   
 -9  -8  -7  -6  -5  -4  -3  -2  -1 

  COMPUTERS[ 4 : 7 ]     =  UTE
  COMPUTERS[ 2 : 5 : 2 ] =  MU
  COMPUTERS[-5 : 1 :-1 ] =  UPM
  COMPUTERS[ 4 ]         =  U
  COMPUTERS[-4 :-6 :-1 ] =  TU
  COMPUTERS[ 2 :-3 : 1 ] =  MPUT
  COMPUTERS[ 2 :-3 :-1 ] =  
  COMPUTERS[   :   :-1 ] =  SRETUPMOC
  COMPUTERS[-5 :   ]     =  UTERS
  COMPUTERS[-5 : 0 :-1 ] =  UPMO
  COMPUTERS[-5 :   :-1 ] =  UPMOC
  COMPUTERS[-1 : 1 :-2 ] =  SEUM

但是我没有得到除了中三以外的其他字母

EXPECTED OUTPUT
Ex:
COMPUTERS =  COMERS (only first three and last three not the middle three letters (PUT))

有人能告诉我如何从开始和结束时取信(:3和6:)

3 个答案:

答案 0 :(得分:3)

那不是一片,那是两片:

word[:3] + word[-3:]

答案 1 :(得分:1)

您可以将副本复制到列表中,删除中间,然后转换回来:

>>> computers = list('COMPUTERS')
>>> del computers[3:-3]
>>> ''.join(computers)
COMERS

答案 2 :(得分:1)

如果要删除字符串的中间部分,则必须使用两个切片:

>>> string="COMPUTERS"
>>> string[:len(string)//3]+string[-len(string)//3:]
'COMERS'