Python:如何在字符串分割结果中包含定界符,并在结果列表的定界符前面添加一个单词?

teststring ='two snote words test note test'

print(teststring.partition('note'))

获取输出:('two snote words test ','note',' test')

但是我想要如下所示的输出(这里“ bold”是我要在比赛前添加的变量):

['two s',bold,'words test',bold.'note','test']
liufei0225 回答:Python:如何在字符串分割结果中包含定界符,并在结果列表的定界符前面添加一个单词?

不带分隔符的分割字符串,然后将分割列表中的第ith个字符串加上字符串和分隔符添加到新列表中。

plus_string = 'bold'
delimiter = 'note'
teststring ='two snote words test note test'
splited = teststring.split(delimiter)
result = []

for s in splited:
    result.append(s)

    if splited.index(s) == len(splited) - 1:
        # Do not append plus_string and delimiter
        # to the end of the list.
        break

    result.append(plus_string)
    result.append(delimiter)

print(result)

将打印:

['two s','bold','note',' words test ',' test']
本文链接:https://www.f2er.com/2935098.html

大家都在问