如何在python中使用切片运算符提取中间部分以外的字母?
How to extract letters except from middle part by using slice operator in python?
我试图理解以下示例的所有可能性。
+---+---+---+---+---+---+---+---+---+
| 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:)
那不是一片,那是两片:
word[:3] + word[-3:]
您可以将副本复制到列表中,删除中间部分,然后再转换回来:
>>> computers = list('COMPUTERS')
>>> del computers[3:-3]
>>> ''.join(computers)
COMERS
如果你想删除字符串的中间部分你必须使用两个切片:
>>> string="COMPUTERS"
>>> string[:len(string)//3]+string[-len(string)//3:]
'COMERS'
我试图理解以下示例的所有可能性。
+---+---+---+---+---+---+---+---+---+
| 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:)
那不是一片,那是两片:
word[:3] + word[-3:]
您可以将副本复制到列表中,删除中间部分,然后再转换回来:
>>> computers = list('COMPUTERS')
>>> del computers[3:-3]
>>> ''.join(computers)
COMERS
如果你想删除字符串的中间部分你必须使用两个切片:
>>> string="COMPUTERS"
>>> string[:len(string)//3]+string[-len(string)//3:]
'COMERS'