📜  Python – 从字符串列表中删除后缀

📅  最后修改于: 2022-05-13 01:55:03.998000             🧑  作者: Mango

Python – 从字符串列表中删除后缀

有时,在处理数据时,我们可能会遇到一个问题,即我们需要过滤字符串列表,以便删除以特定后缀结尾的字符串。让我们讨论可以执行此任务的某些方式。

方法 #1:使用循环 + remove() + endswith()
以上功能的组合可以解决这个问题。在此,我们删除使用循环访问的以特定后缀结尾的元素并返回修改后的列表。

# Python3 code to demonstrate working of
# Suffix removal from String list
# using loop + remove() + endswith()
  
# initialize list 
test_list = ['allx', 'lovex', 'gfg', 'xit', 'is', 'bestx']
  
# printing original list 
print("The original list : " + str(test_list))
  
# initialize suffix
suff = 'x'
  
# Suffix removal from String list
# using loop + remove() + endswith()
for word in test_list[:]:
    if word.endswith(suff):
        test_list.remove(word)
  
# printing result
print("List after removal of suffix elements : " + str(test_list))
输出 :
The original list : ['allx', 'lovex', 'gfg', 'xit', 'is', 'bestx']
List after removal of suffix elements : ['gfg', 'xit', 'is']

方法 #2:使用列表理解 + endswith()
这是可以执行此任务的另一种方式。在这种情况下,我们不会就地执行删除,而是重新创建没有与后缀匹配的元素的列表。

# Python3 code to demonstrate working of
# Suffix removal from String list
# using list comprehension + endswith()
  
# initialize list 
test_list = ['allx', 'lovex', 'gfg', 'xit', 'is', 'bestx']
  
# printing original list 
print("The original list : " + str(test_list))
  
# initialize suff
suff = 'x'
  
# Suffix removal from String list
# using list comprehension + endswith()
res = [ele for ele in test_list if not ele.endswith(suff)]
  
# printing result
print("List after removal of suffix elements : " + str(res))
输出 :
The original list : ['allx', 'lovex', 'gfg', 'xit', 'is', 'bestx']
List after removal of suffix elements : ['gfg', 'xit', 'is']