在Python3中摆脱常见子串前缀的最佳方法是什么?

时间:2018-01-17 14:38:07

标签: python string python-3.x substring

假设我们有字符串和字符串列表:

字符串:

  • str1 = <common-part>

字符串列表:

[<common-part>-<random-text-a>, <common-part>-<random-text-b>]

获得此类列表的最佳(在可读性和代码纯度的情况下)是什么:

[<random-text-a>, <random-text-b>]

5 个答案:

答案 0 :(得分:5)

我会使用os.path.commonprefix计算所有字符串的公共前缀,然后对字符串进行切片以删除该前缀(此函数位于os.path模块中但不检查路径分隔符,它&# 39;可用于通用语境中):

import os

p = ["<common-part>-<some-text-a>", "<common-part>-<random-text-b>"]
commonprefix = os.path.commonprefix(p)

new_p = [x[len(commonprefix):] for x in p]

print(new_p)

结果(因为commonprefix""<common-part>-<"):

['some-text-a>', 'random-text-b>']

注释:

  • 此方法允许使用事先未知的完整动态前缀。通过反转琴弦,还可以删除通用后缀。
  • 最好使用len来对结果进行切片,而不是str.replace():它的速度更快,而且它只会删除字符串的开头,因为我们< em> know 所有字符串都以此前缀开头。

答案 1 :(得分:2)

你可以使用列表推导,它们非常pythonic:

[newstr.replace(str1, '', 1) for newstr in list_of_strings]

newstr.replace(str, '', 1)只会替换第一次出现的str1。 感谢@ ev-kounis建议

答案 2 :(得分:2)

MyList = ["xxx-56", "xxx-57", "xxx-58"]
MyList = [x[len(prefix):] for x in MyList] # for each x in the list, 
                                 # this function will return x[len(prefix):] 
                                 # which is the string x minus the length of the prefix string

print(MyList)

---> ['56', '57', '58']

答案 3 :(得分:2)

我会做的......

common = "Hello_"
lines = ["Hello_1 !", "Hello_2 !", "Hello_3 !"]

new_lines = []
for line in lines:
    # Finding first occurrence of the word we want to remove.
    startIndex = line.find(common) + len(common)
    new_lines.append(line[startIndex:])

print new_lines

自从我们参与其中以来,只测试Jean-FrançoisFabre的表现:

from timeit import timeit
import os

def test_fabre(lines):
    # import os

    commonprefix = os.path.commonprefix(lines)
    return [x[len(commonprefix):] for x in lines]

def test_insert(common, lines):
    new_lines = []
    for line in lines:
        startIndex = line.find(common) + len(common)
        new_lines.append(line[startIndex:])
    return new_lines

print timeit("test_insert(common, lines)", 'from __main__ import test_insert; common="Hello_";lines = ["Hello_1 !", "Hello_2 !", "Hello_3 !"]')
print timeit("test_fabre(lines)", 'from __main__ import test_fabre; lines = ["Hello_1 !", "Hello_2 !", "Hello_3 !"]')

# test_insert outputs : 2.92963575145
# test_fabre outputs : 4.23027790484 (with import os OUTside func)
# test_fabre outputs : 5.86552750264 (with import os INside func)

答案 4 :(得分:0)

str1 = "hello"
list1 = ["hello1", "hello2", "hello3"]
list2 = []
for i in list1:
    list2.append(i.replace(str1,""))
print list2

这是你能做的最简单的方法。

相关问题