Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/349.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:list strip overkill_Python_List - Fatal编程技术网

Python:list strip overkill

Python:list strip overkill,python,list,Python,List,我只想删除列表中的“.SI”,但如果删除列表中任何包含S或I的内容,则会造成过度杀伤力 ab = ['abc.SI','SIV.SI','ggS.SI'] [x.strip('.SI') for x in ab] >> ['abc','V','gg'] output which I want is >> ['abc','SIV','ggS'] 有什么优雅的方法吗?因为我的列表很长,所以不喜欢使用for循环为什么要使用此[x[:-3]for x in ab]为什么要删

我只想删除列表中的“.SI”,但如果删除列表中任何包含S或I的内容,则会造成过度杀伤力

ab = ['abc.SI','SIV.SI','ggS.SI']
[x.strip('.SI') for x in ab]
>> ['abc','V','gg']

output which I want is 
>> ['abc','SIV','ggS']

有什么优雅的方法吗?因为我的列表很长,所以不喜欢使用for循环

为什么要使用此
[x[:-3]for x in ab]
为什么要删除?您可以使用
.replace()

输出:

['abc', 'SIV', 'ggS']
(这将在任何地方删除
.SI
,如果您只想在最后删除它,请查看其他答案)


文档中解释了
strip()
不起作用的原因:

chars参数不是前缀或后缀;相反,其值的所有组合都被剥离


因此,它将删除作为参数传递的字符串中的任何字符。

使用
split
而不是
strip
,并获取第一个元素:

[x.split('.SI')[0] for x in ab]

如果只想从末尾删除子字符串,正确的方法是:

>>> ab = ['abc.SI','SIV.SI','ggS.SI']
>>> sub_string = '.SI'

#       checks the presence of substring at the end
#                                   v
>>> [s[:-len(sub_string)] if s.endswith(sub_string) else s for s in ab]
['abc', 'SIV', 'ggS']
因为
str.replace()
(如中所述)会删除子字符串,即使它位于字符串的中间。例如:

>>> 'ab.SIrt'.replace('.SI', '')
'abrt'

为条带提供了要删除的前导字符和尾随字符集,而不是模式。如果它们都需要删除最后3个字符:
[x[:-3]表示ab中的x]
>>> 'ab.SIrt'.replace('.SI', '')
'abrt'